创建线程的四种方式

  • 继承Thread类
  • 实现Runnable接口
  • 实现Callable接口:如果需要线程执行完得到一个返回值,选择此方式
  • 通过ThreadPoolExecutor线程池获取线程

 1、继承Thread类

public class ThreadDemo extends Thread {
    @Override
    public void run() {
        System.out.println("This is my customized thread.");
    }

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

2、实现Runnable接口

public class RunnableDemo implements Runnable {
    @Override
    public void run() {
        System.out.println("This is my customized thread.");
    }

    public static void main(String[] args) {
        RunnableDemo runnableDemo = new RunnableDemo();
        Thread thread = new Thread(runnableDemo);
        thread.start();
    }
}

3、实现Callable接口

public class CallableDemo implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println("当前线程:" + Thread.currentThread().getName());
        return "Hello, this is response value.";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableDemo callableDemo = new CallableDemo();
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Future<String> future = executorService.submit(callableDemo);
        // Future.get()是一个阻塞方法,会阻塞主线程
        System.out.println(Thread.currentThread().getName() + "########" + future.get());
    }
}

4、通过ThreadPoolExecutor线程池获取线程

public class ThreadPoolDemo implements Runnable {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        //ExecutorService executorService = Executors.newSingleThreadExecutor();
        //ExecutorService executorService = Executors.newCachedThreadPool();
        //ExecutorService executorService = Executors.newScheduledThreadPool(2);
        for (int i = 0; i < 10; i ++) {
            executorService.execute(new ThreadPoolDemo());
        }
        executorService.shutdown();
    }

    @Override
    public void run() {
        try {
            System.out.println("当前运行的线程是" + Thread.currentThread().getName());
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值