penglongli / blog

18 stars 1 forks source link

线程的创建和状态 #108

Open penglongli opened 6 years ago

penglongli commented 6 years ago

线程的创建和状态

线程的创建

线程的创建有两种方式,一种是继承 Thread 类,一种是实现 Runnable 接口

继承 Thread

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.start() 方法,而不是 Thread.run() 方法。这是因为如果调用 run() 方法,则会在当前线程中串行执行 run() 方法。

如下:

static class MyRunnable implements Runnable {
        @Override
        public void run() {
            try {
                // block for some time
                Thread.sleep(3000);
                System.out.println("Thread run.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        runnable.run();
        System.out.println(1);
    }

此时,必须等待 runnable.run() 方法串行执行完后,才能输出 1

线程的状态

线程的状态分为如下:

这里要简单说一下线程的中断: