美文网首页
线程实现三种方法

线程实现三种方法

作者: 小明怕黑 | 来源:发表于2019-03-07 21:30 被阅读0次

    实现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());
        }
    

    相关文章

      网友评论

          本文标题:线程实现三种方法

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