java线程(二)(创建线程的5种方法)

20221129:从正定方舱出来了,哇,呼吸呼吸新鲜空气的感觉真好,隔壁河北工商职业学院的小哥,忘记加他微信,自己的手机没信号,看小哥打的csgo和 植物僵尸人大战挺好看的,加上这小哥微信就好了,回头教教我打,哇哈哈哈哈。

 

    static class MyThread extends Thread {
        @Override
        public void run() { System.out.println("1.Hello MyThread!"); }
    }

    /**
     * 这种方式更好,因为实现了runnable之后还可以实现其他类,而一旦继承了Thread之后就不能
     * 从其他类继承了。
     * */
    static class MyRun implements Runnable{
        @Override
        public void run() {
            System.out.println("2.Hello MyRun");
        }
    }

    static class MyCall implements Callable<String> {
        @Override
        public String call() throws Exception {
            return "5.successss";
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new MyThread().start();
        new Thread(new MyRun()).start();
        new Thread(()->{
            System.out.println("4.Hello Lambda!");
        }).start();
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(()->{
            System.out.println("3.Hello ThreadPool");
        });

        //5. Future可以带有返回值,也是利用线程池来实现
        Future<String> f = service.submit(new MyCall());
        try {
            String s = f.get();
            System.out.println(s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        service.shutdown();

        //6.也可以自己写FutureTask,只是没有线程池方便
        FutureTask<String> task = new FutureTask<>(new MyCall());
        Thread t = new Thread(task);
        t.start();
        System.out.println(task.get()); //get方法会同步等待返回.
    }

 

posted @ 2022-11-29 21:25  宝宝佩恩天道  阅读(23)  评论(0编辑  收藏  举报