线程实现三种方法

实现Runable

    public static class Thread1 implements Runnable{

        @Override
        public void run() {
            System.out.println("thread1 运行......");
        }
    }

运行:

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

继承Thread

    public static class Thread2 extends Thread{
        public void run() {
            System.out.println("thread2 运行......");
            System.out.println(Thread.currentThread().getName());
        }
    }

运行:

    public static void main(String[] args) {
        Thread thread2 = new Thread2();
        thread2.setName("Thread_Name_2");
        thread2.start();
    }

实现Callable

    public static class Thread3 implements Callable<Object>{

        @Override
        public Object call() throws Exception {
            return "Helloword";
        }
    }

运行:

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        // 方式一
        FutureTask<Object> futureTask = new FutureTask<Object>(new Thread3());
        executor.execute(futureTask);
        Object object = futureTask.get(5, TimeUnit.SECONDS);
        System.out.println(object.toString());
        
        //或者方式二
        Future<?> submit = executor.submit(new Thread3());
        Object object2 = submit.get(5, TimeUnit.SECONDS);
        System.out.println(object2.toString());
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容