java10 -02 notify()

notify() :通知 只能唤醒一个 随机的

通知是锁对象的方法

调通知的话 就把等待队列中某一个线程唤醒,把它唤醒后,它可以在去抢CPU。

对于生产者,一旦当了元素,即消费者就可以取走了。

sleep():放弃CPU的抢占权,跟锁对象的监控权无关

wait():相当于线程停止,要想再次运行,就要用notify() 通知模式。

让当前线程进入到锁对象的等待队列中去,同时释放锁旗标。

-------------------------------------------源码

class TenProductCustor4{
public static void main(String[] agrs) {
MyList mylist =new MyList();
Productor p =new Productor(mylist);
Productor p1 =new Productor(mylist);
Cusumer c =new Cusumer(mylist);
p.start();
p1.start();
c.start();

}

}

//用类封装集合,同步要么往里放,要么取。
class MyList{
private int MAX =100;
private java.util.List<Integer> list =new java.util.LinkedList<Integer>();
//同步方法,满了即等待。wait方法是object定义的,sleep是线程类的方法。要用Thread.sleep() 锁里面是有等待机制的,任何对象都可以是锁。同步方法以当前对象MyList作为锁。
public synchronized void addLast(Integer i){
//如果大于这个数就等待
while(list.size()>=MAX){
try{
wait();
}

catch(Exception e){

}
}
list.add(i);
//添加完一个元素,通知一下。通知等待的队列。通知方法不会释放锁旗标
System.out.println("库存=》" +list.size());
notify();
}

public synchronized Integer removeFirst(){
while(list.size()==0){
try{
wait();
}

catch(Exception e){

}
}
notify();
int no = list.remove(0);
System.out.println("remove=》" +list.size());
return no;
}
}

//生产者

class Productor extends Thread{
static int i=1;
//创建一个集合
private MyList mylist;
public Productor(MyList mylist){
this.mylist=mylist;
}

public void run(){

while(true){
mylist.addLast(i);
System.out.println("生产了=====》》" +i);
i++;
}
}
}
//消费者
class Cusumer extends Thread{
private MyList mylist;
public Cusumer(MyList mylist){
this.mylist=mylist;
}

public void run(){
while(true){
int no =mylist.removeFirst();
System.out.println("消费了=====》》" +no);
}
}
}

------------------------------------------------------------------

同步代码

class TenProductCustorwait5{
public static void main(String[] agrs) {
Pool pool = new Pool();
Producer p = new Producer("p"+pool);
Consumer c = new Consumer("c"+pool);
p.start();
c.start();

}

}
class Pool{
private int Max =100;
private java.util.List<Integer> list =new java.util.LinkedList<Integer>();

public void addLast(int i){
//以当前对象Pool做锁,把当前线程放到锁的队列中去
synchronized(this){
while(list.size()>= Max){
try{
wait();
}

catch(Exception e){

}
}
list.add(new Integer(i));
this.notify();//通知和等待都是掉锁的方法
}
}

public int Remove(){
//以当前对象Pool做锁,把当前线程放到锁的队列中去
synchronized(this){
while(list.size()==0){
try{
wait();
}

catch(Exception e){

}
}
int no =list.remove(0);
this.notify();
return no;
}
}

}

class Producer extends Thread{
private Pool pool;

private String name;
static int i =1;
public Producer( String name,Pool pool){
this.pool =pool;

this.name=name;
}
public void run(){
while(true){
pool.addLast(i++);
System.out.println("生产者"+i);
}
}
}

class Consumer extends Thread{

private String name;
private Pool pool;
public Consumer(String name,Pool pool){
this.pool =pool;

this.name=name;
}
public void run(){
while(true){
int no = pool.Remove();
System.out.println("消费了"+no);
}
}
}

原文地址:https://www.cnblogs.com/simly/p/10553139.html