1.Object类中与线程相关的方法
wait() -等待
notify() -唤醒
notifyAll() -唤醒所有线程
这些方法为什么在Object类下,而不是在Thread类下?
某个对象调用这些方法以改变操作这个对象的线程的状态
比如:当一个对象是由两个线程操作的,当这个对象调用wait()方法后,这两个线程就都进入等待状态
2.线程的生命周期
新建、就绪、运行、阻塞、销毁
3.synchronized
它的作用是保证在同一时刻,其修饰的代码块或方法只有一个线程执行,以保证达到并发安全的效果
方法上的synchronized形式
class Test1 {
public synchronized void test()
{
}}
//等价于
class Test2{
public void test() {
synchronized (this){}
}
}
4.自己的阻塞队列代码实现
基于生产者消费者模型实现的队列的原理
生产者:产生数据存入仓库
仓库:定容量,满了,生产者暂停,唤醒消费者,空了,消费者暂停,唤醒生产者
消费者:从仓库出取出数据
队列的具体实现
public class MyBlockingQueue <E>{
int limit;
private Queue<E> queue=new LinkedList<>();
public MyBlockingQueue(int limit) {
this.limit = limit;
}
public synchronized void enQueue(E e) throws InterruptedException {
while(this.limit==this.queue.size()){
//仓库满了
wait();
}
//生产线程等待
if(this.queue.isEmpty()){
notifyAll();
}
//生产线程唤醒
queue.add(e);
}
public synchronized E deQueue() throws InterruptedException {
while(this.queue.isEmpty()){
// System.out.println("wait!");
wait();
}
//消费线程等待
if(this.limit==this.queue.size()){
notifyAll();
}
//消费线程唤醒
return this.queue.remove();
}
public boolean isEmpty(){
return this.queue.isEmpty();
}
public int size(){
return this.queue.size();
}
}
5.模型在流水线中的作用及实现
模型在流水线中的作用就是限流
当B线程执行B任务很快,A线程完成A任务的速度跟不上的时候,B的任务池中为空,且处于等待状态
另外,任务池可以设置上限,当达到上限后,任务池中任务数不会增加,但仍可以不断完成C任务,D任务
并不能解决的问题
首先产生总任务的任务池仍是定容量的,不可以在容量为500的任务池中一次性加入1000个,线程会陷入等待状态
所有线程的结束仍需要像上一篇博客中所写的结束方式一样,设置开关,以结束所有线程
具体代码改变
public void run() {
while(true){
Task task;
// System.out.println("线程B在执行........");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
task=queueB.deQueue();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
task.TaskB();
try {
queueC.enQueue(task);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}