@File
2020-04-09T14:34:04.000000Z
字数 3095
阅读 122
java
web
Thread
类,重写 run()
方法
public class MyThread extends Thread {
@Override
public void run() {
// 业务逻辑
}
/**
* 模拟调用
*/
public static void main(String[] args) {
MyThread myThread = new MyThread();
// 启动线程
myThread.start();
}
}
Runnable
接口,实现 run()
方法
public class MyRunnable implements Runnable{
@Override
public void run() {
// 业务逻辑
}
/**
* 模拟调用
*/
public static void main(String[] args) {
// 吧 Runnable 实现类的实例作为参数实例化 Thread
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
// 启动线程
thread.start();
}
}
start()
启动线程
Thread thread = new Thread();
thread.start();
join()
等待线程start()
后面
// 启动了某个线程
thread.start();
// 等待上面的线程结束后再往下执行
thread.join();
isInterrupted()
是否已中断
thread.isInterrupted();
currentThread()
查看当前线程信息
// 查看线程id
Thread.currentThread().getId()
// 查看线程名称
Thread.currentThread().getName()
sleep()
线程延时
// 方法一:延时 1000 毫秒
Thread.sleep(1000)
// 方法二:延时 1 秒
TimeUnit.SECONDS.sleep(1);
synchronized
同步锁
// 锁类
public class synchronized Demo {
// 锁对象方法
public synchronized test() {
// 锁对象业务块
synchronized(this){}
}
// 锁类方法
public synchronized static test() {
// 锁类业务块
synchronized(Demo.class){}
}
}
/**
* 创建线程池
* @param int corePoolSize 核心线程数
* @param int maximumPoolSize 最大线程数
* @param long keepAliveTime 空闲线程存活时间
* @param TimeUnit unit 时间单位
* @param BlockingQueue<Runnable> workQueue 任务队列
* @param ThreadFactory threadFactory 线程创建的方式
* @param RejectedExecutionHandler handler 拒绝策略
*/
ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 8, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5));
// 提交任务
pool.execute(() -> {
// 任务逻辑
});
newSingleThreadExecutor
单线程的线程池
Executors.newSingleThreadExecutor();
newFixedThreadExecutor
固定大小的线程池
Executors.newFixedThreadExecutor();
newCacheThreadExecutor
可缓存的线程池
Executors.newCacheThreadExecutor();
newScheduleThreadExecutor
无限大的线程池
Executors.newScheduleThreadExecutor();
// 创建大小为2的线程池
ScheduledExecutorService pool = new ScheduledThreadPoolExecutor(2);
// 5秒后执行的任务
pool.schedule(() -> {
// 任务逻辑
}, 5, TimeUnit.SECONDS);
// 相隔2秒执行一次的任务
pool.schedule(() -> {
// 任务逻辑
}, 0, 2, TimeUnit.SECONDS);
submit()
| execute()
提交任务shutdown()
停止线程池shutdownNow()
立即停止线程池isShutdown()
是否正在关闭线程池isTerminated()
是否已经关闭线程池awaitTermination()
等待线程关闭