public class Test {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread run.");
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现 Runnable
public class Test {
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread run.");
}
}
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
线程的创建和状态
线程的创建
线程的创建有两种方式,一种是继承 Thread 类,一种是实现 Runnable 接口
继承 Thread
实现 Runnable
如下:
此时,必须等待
runnable.run()
方法串行执行完后,才能输出1
线程的状态
线程的状态分为如下:
这里要简单说一下线程的中断:
当线程处于
WAITING
、TIMED_WAITING
状态时(如调用了 wait()、join()、sleep() 等方法将会进入此两种状态),调用 Thread.interrupt 方法,则线程的中断状态将被清除,并抛出InterruptedException
异常举例:
此段代码将会抛出
InterruptedException
异常如果线程处在
RUNNABLE
状态时,通常情况该线程的中断状态会被设置,关于这一块会在“线程中断”中说。