一、线程
1.继承Thread
public static class Thread01 extends Thread {
@Override
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
}
}
Thread thread = new Thread01(); thread.start();//启动线程
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main......start.....");
new Thread01().start();
System.out.println("main......end.....");
}
2.实现Runnable接口
public static class Runable01 implements Runnable {
@Override
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
}
}
启动线程
Runable01 runable01 = new Runable01();
new Thread(runable01).start();
3.实现Callable接口+FutureTask(可以拿到返回结果,处理异常)
public static class Callable01 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}
}
启动线程
FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
new Thread(futureTask).start();
//返回值futureTask.get()
System.out.println(futureTask.get());
4.线程池,给线程池提交任务
通过如下两种方式初始化线程池
Executors.new…… //或者+
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit unit, workQueue, threadFactory, handler);==>七大参数
1.@param corePoolSize 池中一直保持的线程的数量,即使线程空闲。除非设置了 {@code allowCoreThreadTimeOut
2.@param maximumPoolSize 池中允许的最大的线程数
3.@param keepAliveTime 当线程数大于核心线程数的时候,线程在最大多长时间没有接到新任务就会终止释放, 最终线程池维持在 corePoolSize 大小
4.@param unit 时间单位
5.@param workQueue 阻塞队列,用来存储等待执行的任务,如果当前对线程的需求超过了 corePoolSize 大小,就会放在这里等待空闲线程执行。
6.* @param threadFactory 创建线程的工厂,比如指定线程名等
7.@param handler 拒绝策略,如果线程满了,线程池就会使用拒绝策略。