实现消费者与生产者
生产者:生产一个产品,当被消费者消费后才会生产下一个产品;
消费者:消费一个产品,当生产者生产出一个产品后,才可消费;
创建一个产品类;
一个生产者线程;
一个消费者线程;
实现线程同步,两个线程都操作了产品类,应该在产品类中设置synchronized关键字;
使用等待与唤醒操作,实现同步:
Object类
public final void wait()throws InterruptedException //等待:死等
public final void wait(long timeout) throws InterruptedException //设置等待时间
public final void wait(long timeout,int nanos) throws InterruptedException //设置等待时间
public final void notify() //唤醒第一个等待线程
public final void notifyAll() //唤醒全部等待线程
/**
* 设置生产消费标记
* symbol,当symbol为true时,允许生产,不允许消费;
* 当symbol为false,允许消费,不允许生产;
*/
class Message
{
private String name;
private String character;
private boolean symbol=true;
public synchronized String get() {
if(symbol)//还未生产;
{
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
this.symbol=true;
super.notify();
}
return this.name+"*********"+this.character;
}
public synchronized void set(String name,String character) {
if(!symbol)
{
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.name=name;
this.character = character;
this.symbol=false;//已经生产过了;
super.notify();//唤醒等待线程;
}
}
class Product implements Runnable{
private Message mes;
public Product(Message mes)
{
this.mes=mes;
}
@Override
public void run() {
for(int i=0;i<100;i++)
{
if(i%2==00)
{
this.mes.set("杨幂","演技差");
}
else
{
this.mes.set("陈坤","演技好");
}
}
}
}
class Customer implements Runnable
{
private Message mes;
public Customer(Message mes)
{
this.mes=mes;
}
@Override
public void run() {
for(int i=0;i<100;i++)
{
System.out.println(this.mes.get());
}
}
}
public class ProductCustomer {
public static void main(String[] args) {
Message mes=new Message();
new Thread(new Product(mes)).start();
new Thread(new Customer(mes)).start();
}
}