实现线程的多种方式

假如想象 提交于 2020-03-12 22:22:52

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!