标签:set sys while cot tac rgs 对象锁 read 结果
1.sleep()是Thread类的方法;而wait(),notify(),notifyAll()是Object类中定义的方法;代码实现:
package ProducerCon;
import java.util.ArrayList;
import java.util.List;
public class ProducerCoThread {
public static void main(String[] args) {
List list = new ArrayList<>();
Thread t1 = new Thread(new Producer(list));
Thread t2 = new Thread(new Consumer(list));
t1.setName("生产者线程");
t2.setName("消费者线程");
t1.start();
t2.start();
}
}
class Producer implements Runnable{
private List list;
public Producer(List list) {
super();
this.list = list;
}
public void run() {
while(true) {
synchronized(list) {
if(list.size() > 0) {
try {
list.wait(); //当前线程进入等待,并释放锁.此时下面执行不了
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object obj = new Object();
list.add(obj);
System.out.println(Thread.currentThread().getName()+"---->"+obj);
list.notify();
}
}
}
}
class Consumer implements Runnable{
private List list;
public Consumer(List list) {
super();
this.list = list;
}
public void run() {
while(true) {
synchronized(list) {
if(list.size() == 0) {
try {
list.wait(); //当前线程进入等待,并释放锁.此时下面执行不了
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object obj = list.remove(0);
System.out.println(Thread.currentThread().getName()+ "---->"+obj);
list.notify();
}
}
}
}
运行结果:
标签:set sys while cot tac rgs 对象锁 read 结果
原文地址:https://blog.51cto.com/14472348/2487692