1、线程创建和启动
1、继承Thread 创建线程
pubilc FirstThread extends Thread{...}
new FirstThread().start()
2、继承Runnable创建线程
pubilc SecondThread extends Runnable{...}
SecondThread th = new SecondThread();
new Thread(th, "新线程").start()
3、 实现Callable接口
FutureTask<Integer> task = new FutureTask<Integer>((Callable<Integer>) () -> {...}
new Thread(task, "新线程").start()
task.get() //子线程执行结束的返回值
2、线程的生命周期
New ---> Runnable ----> Running ----> Blocking ----> Dead
3、控制线程
3.1 join()
在当用执行流中调用其他多线程的join()
3.2 后台程序
如果所有的前台程序都死亡,后台程序会自动死亡
setDaemon(true) // 将此线程设置为后台线程
3.3、sleep()
3.4、线程优先级
setPriority(number) // 线程优先级
4、线程同步
4.1、线程代码块
synchronized(obj){
...
// 同步代码块部分
}
4.2、同步方法
public synchronized void draw(double drawAccount){
...
}
4.3 释放同步锁的方法
1、同步方法、同步代码块执行结束
2、同步方法、同步代码出现了未处理的error exception
3、同步方法、同步代码遇到了break、return
4.4 同步锁(Lock)
// 定于锁对象
private final ReentrantLock lock = new ReentrantLock();
// 加锁
lock.lock();
// 解锁
lock.unlock();
5、线程通信
5.1 使用condition控制线程通信
// 显式定义lock对象
private final Lock lock = new ReentrantLock();
// 获得指定的lock对象对应的condition
private final Condition cond = lock.newCondition();
// 线程阻塞
cond.await();
// 唤起其他线程
cond.signalAll();
5.2 使用阻塞队列 (BlockingQueue) 控制线程
BlockingQueue<String> bq = new ArrayBlockingQueue<String>(2); // 创建阻塞队列
bq.put() // 存
bq.take() // 取
6、线程池
6.1、线程池创建 ExecutorService
// 创建一个具有固定线程数 6 的线程池
ExecutorService pool = Executors.newFixedThreadPool(6);
Runnable trget = () ->{
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "的i值为:"+i);
}
};
pool.submit(trget);
pool.submit(trget);
pool.shutdown();