Java线程创建方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34560242/article/details/81134989

第一种、自定义类继承Thread,重写run()方法

public class Test {

    public static void main(String[] args) {
        new Demo().start();
    }
}

class Demo extends Thread {

    @Override
    public void run() {
        System.out.println("第一种创建方式");
    }
}

第二种、自定义类实现Runnable接口

public class Test {

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

class Demo implements Runnable {
    @Override
    public void run() {
        System.out.println("第二种创建方式");
    }
}

第三种、自定义类实现Callable接口

public class Test {

    public static void main(String[] args) {
        Demo demo = new Demo();
        // 引用FutureTask支持
        FutureTask<String> ft = new FutureTask(demo);
        new Thread(ft).start();
        try {
            // 获取线程结果,注意:当FutureTask没有执行完的时候,是无法获取结果的,效果类似闭锁。
            System.out.println(ft.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Demo implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("第三种创建方式");
        return "第三种创建方式";
    }
}

第四种、线程池

线程池:提供了一个线程队列,队列中保存着所有等待状态的线程,避免了线程的创建与销毁的额外开销,提高了响应速度。
这里写图片描述

相关工具方法:

  • Executors.newCachedThreadPool():无界线程池,可以进行自动线程回收
  • Executors.newFixedThreadPool(int):固定大小线程池
  • Executors.newSingleThreadExecutor():单个后台线程

举例:
1、Runnable 接口

public class HelloWorld {

    public static void main(String[] args) {
        // 创建数量为5的线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        // 任务提交给线程池
        for (int i = 0; i < 10; i++) {
            threadPool.submit(new TestThreadPool());
        }
        // 关闭线程池
        threadPool.shutdown();
    }
}

class TestThreadPool implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " : " + i);
        }
    }
}

2、Callable 接口

public class HelloWorld {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建数量为5的线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        // 任务提交给线程池
        ArrayList<Future<Integer>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<Integer> future = threadPool.submit(() -> {
                int sum = 0;
                for (int j = 0; j < 10; j++) {
                    sum += j;
                }
                return sum;
            });
            futures.add(future);
        }
        // 关闭线程池
        threadPool.shutdown();
        for (Future<Integer> future : futures) {
            System.out.println(future.get());
        }
    }
}
  • new ScheduledThreadPoolExecutor():创建固定大小的线程池,可以延时或者执行定时任务。

举例:

public class HelloWorld {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建数量为5的线程池
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);
        List<ScheduledFuture<Integer>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            ScheduledFuture<Integer> future = threadPool.schedule(() -> {
                int anInt = new Random().nextInt(100);
                System.out.println(Thread.currentThread().getName() + " : " + anInt);
                return anInt;
            }, 3, TimeUnit.SECONDS);    // 延迟3秒执行任务
            list.add(future);
        }
        threadPool.shutdown();
        for (ScheduledFuture<Integer> future : list) {
            System.out.println(future.get());
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章