生产者和消费者模型:
package thread;
class Producer implements Runnable {
public Producer(Q q) {
this.q = q;
}
Q q;
public void run() {
int i = 0;
while (true) {
/*
synchronized (q) {// 当前线程得到对象q的lock旗标
if (q.bFull) {
try {
q.wait();// 此时当前线程被放置在对象q的等待池中,当前线程释放q的锁旗标
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (i == 0) {
q.name = "zhangsan";
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
q.sex = "male";
} else {
q.name = "lisi";
q.sex = "female";
}
q.bFull = true;
q.notify();// 当另外的线程执行了对象o的notify()方法后,当前线程可能会被从q的等待
// 线程池中释放出来,并且移动到等待线程对象q的锁旗标的线程池中,当当前 //线程得到的锁旗标时就会执行下去
}*/
if (i == 0) {
q.put("zhangsan", "male");
} else {
q.put("lisi", "female");
}
i = (i + 1) % 2;
}
}
}
class Consumer implements Runnable {
public Consumer(Q q) {
this.q = q;
}
Q q;
@Override
public void run() {
while (true) {
/*
* synchronized (q) {
* if (!q.bFull) {
try {
q.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
* }
* if (q.name != "") {
* System.out.print(q.name); q.name = "";
* }
* if (q.sex != "") {
* System.out.println(":" + q.sex); q.sex = "";
* }
* q.bFull = false;
* q.notify(); }
*/
q.get();
}
}
}
class Q {
private String name = "unknown";
private String sex = "unknown";
private boolean bFull = false;
public synchronized void put(String name, String sex) {
if (bFull) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.sex = sex;
bFull = true;
notify();
}
public synchronized void get() {
if (!bFull) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(name);
System.out.println(":" + sex);
bFull = false;
notify();
}
}
调用入口:
public class ThreadCommunation {
public static void main(String[] args) {
Q q = new Q();
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}
}
本文介绍了一个典型的生产者消费者模型实现,通过Java线程同步机制确保数据生产和消费的正确性。模型使用了synchronized关键字和wait/notify方法来协调生产者与消费者的运行。
691

被折叠的 条评论
为什么被折叠?



