美文网首页
【线程】启动线程的三种方式

【线程】启动线程的三种方式

作者: 浅浅星空 | 来源:发表于2019-02-25 15:43 被阅读4次

    1.继承Thread

    public class Thread01 extends Thread {
    
        @Override
        public void run() {
            System.out.println("thread01");
        }
    
    }
    
    class TestThread01 {
        public static void main(String[] args) {
            Thread01 thread01 = new Thread01();
            thread01.start();;
        }
    }
    
    

    2.实现Runnable接口

    public class Thread02 implements Runnable {
        @Override
        public void run() {
            System.out.println("实现Runnable接口");
        }
    }
    
    class TestThread02 {
        public static void main(String[] args) {
            Thread thread = new Thread(new Thread02());
            thread.start();
        }
    }
    

    3.实现Callable接口

    public class Thread03 implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            int i;
            for (i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName());
            }
            return i;
        }
    }
    
    class TestThread03 {
        public static void main(String[] args) {
            Thread03 thread03 = new Thread03();
            FutureTask<Integer> futureTask = new FutureTask<Integer>(thread03);
            Thread thread = new Thread(futureTask);
            thread.start();
    
            try {
                System.out.println(futureTask.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:【线程】启动线程的三种方式

          本文链接:https://www.haomeiwen.com/subject/drjgyqtx.html