`

生产者消费者模式(入门备忘)

 
阅读更多
1.基础类:简单的对num的操作,注意同步
public class SynStackNum {

private int num = 0;

public synchronized void printAdd(String threadName) {
num++;
System.out.println("生产线程: "+ Thread.currentThread().getName()+",threadName="+threadName+", 生产 num ="+num);
}

public synchronized void printDel(String threadName) {
num--;
System.out.println("消费线程: "+Thread.currentThread().getName()+",threadName="+threadName+", 消费  num ="+num);
}


public synchronized int getNum() {
return num;
}

public synchronized void setNum(int num) {
this.num = num;
}
}
2.然后是生产者:
public class ProductThread implements Runnable {
private SynStackNum c;
public String name;

public ProductThread(String name, SynStackNum c) {
this.name = name;
this.c = c;
}

@Override
public void run() {
while (true) {
synchronized (c) {
if (c.getNum() >= 10) {
try {
System.out.println(getClass() + ",数据过多,增加操作 wait...");
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
c.printAdd(name);
c.notify();
System.out.println(this.getClass() + ",增加    notify.........");
try {
// Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}

}

public synchronized SynStackNum getC() {
return c;
}

public synchronized void setC(SynStackNum c) {
this.c = c;
}
}
3.消费者:
package com.my.thread;

public class ComsumThread implements Runnable {
public String name;

private SynStackNum c;

public ComsumThread(String name, SynStackNum c) {
this.name = name;
this.c = c;
}

@Override
public void run() {
while (true) {
synchronized (c) {
try {
// 让当前线程等待,即持有当前对象锁的线程等待
if (c.getNum() <= 1) {
System.out.println(getClass() + ",没有数据,删除操作 wait...");
c.wait();
}
// Thread.sleep(1000);
c.printDel(name);
c.notify();
System.out.println(getClass() + ",删除... notify...........");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

public synchronized SynStackNum getC() {
return c;
}

public synchronized void setC(SynStackNum c) {
this.c = c;
}
}
3.测试主线程:
public class Main {

private SynStackNum c = new SynStackNum();

public static void main(String[] args) {
new Main().start();
}

private void start() {
ComsumThread c1 = new ComsumThread("consum11", c);
ComsumThread c2 = new ComsumThread("consum22", c);
ProductThread p1 = new ProductThread("procdct11", c);
ProductThread p2 = new ProductThread("procdct22",c);

ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(c1);
exec.execute(c2);
exec.execute(p1);
exec.execute(p2);

System.out.println("主线程结束  end..");
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics