生产者消费者
Java多线程之生产者与消费者
***********************核心方法类****************
package test.com;
class Queue
// key
{
int value;
boolean bFull = false;
public synchronized void put(int i) {
if (!bFull) {
value = i;
bFull = true;
notify();// 必须用在synchronized
}
try {
wait();// 必须捕获异常
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized int get() {
if (!bFull)
try {
wait();//进入
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bFull = false;
notify();
return value;
}
}
************************生产者类********************************
package test.com;
class Producter extends Thread
{
Queue q;
Producter (Queue q)
{
this.q=q;
}
public void run()
{
System.out.println(“********producter****start*****”);
for(int i=1;i《10;i++)
{
System.out.println(“producter :”+i);
q.put(i);
}
System.out.println(“********producter*****end****”);
}
}
**********************************************************************
****************************消费者类*********************************
package test.com;
class Consumer extends Thread
{
Queue q;
Consumer(Queue q)
{
this.q=q;
}
public void run()
{
System.out.println(“********Consumer****start*****”);
while(true)
{
System.out.println(“Consumer:”+q.get());
System.out.println(“********Consumer****end*****”);
}
}
}
************************************************************************
*******************************主函数调用类**********************************
package test.com;
public class Test {
public static void main(String[] args) {
Queue q=new Queue();
Producter p=new Producter(q);
Consumer c=new Consumer(q);
p.start();
c.start();
}}
*****************************************************************
OK,实现完毕
wait方法——把线程放入wait set
notify方法——从wait set拿出线程
notifyAll方法——从wait set拿出所有线程
wait、notify、notifyAll是Object类的方法
死锁
package dead;
class Lock implements Runnable{
public Boolean flag;
public Lock(Boolean flag) {
this.flag = flag;
}
static Object lock1 = new Object();
static Object lock2 = new Object();
public void run() {
if(flag){
while(true){
synchronized (lock1) {
System.out.println("if lock1");
synchronized (lock2) {
System.out.println("if lock2");
}
}
}
}else {
while(true){
synchronized (lock2) {
System.out.println("else if lock2");
synchronized (lock1) {
System.out.println("else if lock1");
}
}
}
}
}
}
public class DeadLock {
public static void main(String[] args){
Lock fg1 = new Lock(true);
Lock fg2 = new Lock(false);
Thread t1 = new Thread(fg1);
Thread t2 = new Thread(fg2);
t1.start();
t2.start();
}
}