首页 > 技术文章 > 实现线程的多种方式

huan30 2020-03-12 21:41 原文

1.继承Thread

public class Thread01 extends Thread {
    @Override
    public void run() {
        System.out.println("继承Thread");
    }

    public static void main(String[] args) {
        Thread01 thread01 = new Thread01();
        thread01.start();
    }
}

 

2.实现Runnable

public class Runnable01 implements Runnable {
    @Override
    public void run() {
        System.out.println("实现Runnable");
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable01());
        thread.start();
    }
}

  

3.实现Callable

public class Callable01 implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "实现 Callable";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask task = new FutureTask(new Callable01());
        new Thread(task).start();
        System.out.printf("内容 "+task.get());
    }
}

  源码截图

 

 

 

   

 

 

 

线程的多种状态

public enum State {
        /**
         * 初始状态,尚未启动
         */
        NEW,

        /**
         * 可运行状态,可随时运行
         */
        RUNNABLE,

        /**
         *  线程阻塞,
         */
        BLOCKED,

        /**
         * 等待状态
         */
        WAITING,

        /**
         * 指定时间等待*/
        TIMED_WAITING,

        /**
         * 线程已完成执行
         */
        TERMINATED;
    }

 

 

 

 

 

 

 

 

 

 

 

xxxx

推荐阅读