标签:多线程 生产者 消费者
package com.roger.produceConsumer;
/**
* 生产者和消费者
* 生产的数量需要和消费的数量一致
* @author Roger
*/
public class Main {
public static void main(String[] args) {
// 初始化一个盛放数据的容器
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(c).start();
}
}
/**
* 生产者
* @author Roger
*/
class Producer implements Runnable{
SyncStack ss = null;
Producer(SyncStack ss){
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
Mobile mobile = new Mobile(i);
ss.push(mobile);
System.out.println(Thread.currentThread().getName()+" Producer : " + mobile);
try {
Thread.sleep((int)(Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 消费者
* @author Roger
*/
class Consumer implements Runnable{
SyncStack ss = null;
Consumer(SyncStack ss){
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
Mobile mobile = ss.pop();
System.out.println(Thread.currentThread().getName()+" Consumer : " +mobile);
try {
Thread.sleep((int)(Math.random() * 2));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 需要生产的数据
* @author Roger
*/
class Mobile{
int id; // 生产数据的ID
Mobile(int id){
this.id = id;
}
public String toString(){
return "WoTou : "+id;
}
}
/**
* 盛放数据的容器
* 先进后出
* @author Roger
*/
class SyncStack{
int index = 0;
Mobile[] mobile = new Mobile[6];
public synchronized void push(Mobile wt){
while(index == mobile.length){
try {
// 当前正在访问的线程wait。
// 锁定才能使当前线程wait。
// wait后锁不再归当前线程
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 叫醒一个正在等待当前对象的另一个线程
this.notify();
mobile[index] = wt;
index++;
}
public synchronized Mobile pop(){
while(index == 0){
try {
// 当前正在访问的线程wait。
// 锁定才能使当前线程wait。
// wait后锁不再归当前线程
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 叫醒一个正在等待当前对象的另一个线程
this.notify();
index--;
return mobile[index];
}
}本文出自 “10950988” 博客,请务必保留此出处http://10960988.blog.51cto.com/10950988/1791016
标签:多线程 生产者 消费者
原文地址:http://10960988.blog.51cto.com/10950988/1791016