四种创建多线程的方式

1.四种创建多线程的方式

第一种:继承Thread类
第二种:实现Runnable接口
第三种:Callable接口
第四种:线程池

call()方法比run()方法更加强大
1.call()方法可以有返回值
2.call()方法可以声明抛出异常

import com.jikang.MyApplication;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.sql.Time;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * 四种创建多线程的方式
 *
 * @author yangjikang
 * @date 2019/6/5 14:01
 * @modified By yangjikang
 */
public class TestThreadDome01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //获取当前cpu内核数
        System.out.println(Runtime.getRuntime().availableProcessors());
        //第一种:继承Thread类
        Dome01 dome01 = new Dome01();
        new Thread(dome01).start();
        //第二种:实现Runnable接口
        Dome02 dome02 = new Dome02();
        new Thread(dome02).start();
        //第三种:Callable接口
        FutureTask<Integer> demo03 = new FutureTask<>(new Dome03());
        new Thread(demo03, "demo3").start();
        //第四种:线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                5,
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        threadPoolExecutor.execute(()-> System.out.println("。。。"));
        threadPoolExecutor.shutdown();
        Integer integer = demo03.get();//要求获取Callable线程的执行时间,如果没有出现结果就会造成阻塞,所以一般get()方法放在最后
        System.out.println(integer);
    }

}

class Dome01 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {

        }
    }
}

class Dome02 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
        }
    }
}

class Dome03 implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        long start = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(5);
        long end = System.currentTimeMillis();
        return Math.toIntExact(end - start);
    }
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值