实现生产者和消费者模式,重要的几点:
1. 持同一把锁
2. 线程共享标识,用于线程切换
3.等待和通知(Object方法:wati()/notify() nofifyAll()
Condition方法:await()/ signal() signalAll())
一、使用Condition方法:await()/ signal() signalAll()实现,交替打印
package cho1;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Work
{
/**
* 对象锁
*/
private ReentrantLock lock = new ReentrantLock();
/**
* Condition
*/
private Condition con = lock.newCondition();
/**
* 线程通信标志
*/
private volatile boolean flag = false;
// 输出BBBB
public void doWorkB()
{
try
{
lock.lock();
if (flag == false)
{
// 等待唤醒,释放锁
con.await();
}
System.out.println("BBBBBBBBB");
Thread.sleep(1000);
flag = false;
// 通知等待的线程 只通知con.await()
con.signalAll();
} catch (Exception e)
{
e.printStackTrace();
} finally
{
lock.unlock();
}
}
// 输出AAAAA
public void doWorkA()
{
try
{
lock.lock();
if (flag == true)
{
con.await();
}
System.out.println("AAAAA");
Thread.sleep(1000);
flag = true;
con.signal();
} catch (Exception e)
{
e.printStackTrace();
} finally
{
lock.unlock();
}
}
}
package cho1;
public class Run
{
public static void main(String[] args)
{
// 创建work实例
Work work = new Work();
// 启动线程
new Thread(new Runnable()
{
@Override
public void run()
{
while (true)
{
work.doWorkB();
}
}
}).start();
// 启动线程
new Thread(new Runnable()
{
@Override
public void run()
{
while (true)
{
work.doWorkA();
}
}
}).start();
}
}
二、使用Object方法:wati()/notify() nofifyAll(),实现交替打印
package ch02;
public class Work
{
private volatile boolean flag = false;
private final Object lock = new Object();
public void doWorkB()
{
synchronized (lock)
{
try
{
if (flag == false)
{
lock.wait();
}
System.out.println("BBBBBBBBB");
flag = false;
lock.notifyAll();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
public void doWorkA()
{
synchronized (lock)
{
try
{
if (flag == true)
{
lock.wait();
}
System.out.println("AAAAA");
flag = true;
lock.notifyAll();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
package ch02;
public class Run
{
public static void main(String[] args)
{
Work work = new Work();
new Thread(new Runnable()
{
@Override
public void run()
{
while (true)
{
work.doWorkB();
}
}
}).start();
new Thread(new Runnable()
{
@Override
public void run()
{
while (true)
{
work.doWorkA();
}
}
}).start();
}
}
两种方式的输出: