标题:[分享][经验][开源]JAVA多线程经典实例
取消只看楼主
冰的热度
Rank: 2
等 级:禁止访问
威 望:5
帖 子:404
专家分:0
注 册:2006-12-2
 问题点数:0 回复次数:0 
[分享][经验][开源]JAVA多线程经典实例

以下是生产者和消费者问题,是JAVA多线程经典实例,经过我的修改,更加完美,使初学者简单易懂!

public class SharedBufferTest
{
public static void main(String args[])
{
SynchronizedBuffer sharedLocation=new SynchronizedBuffer();
StringBuffer columnHeads=new StringBuffer("当前状态");
columnHeads.setLength(40);
columnHeads.append("第n次\t有无产品(1.有/0.没有)");
System.out.println(columnHeads);
System.out.println();
sharedLocation.displayState("初始化");
Producer p=new Producer(sharedLocation);
Consumer c=new Consumer(sharedLocation);

p.start();
c.start();
}
}

interface Buffer
{
public void set(int value);
public int get();
}
class SynchronizedBuffer implements Buffer
{
private int buffer=-1;
private int occupiedBufferCount=0;
public synchronized void set(int value)
{
String name=Thread.currentThread().getName();
while(occupiedBufferCount==1)
{
try
{
System.out.println(name+" 试图生产产品");
displayState("已经有产品 "+name+" 等待");
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
buffer=value;
++occupiedBufferCount;
displayState(name+" 生产 "+buffer);
notify();
}
public synchronized int get()
{
String name=Thread.currentThread().getName();
while(occupiedBufferCount==0)
{
try
{
System.out.println(name+" 试图去买");
displayState("无产品 "+name+" 等待");
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
--occupiedBufferCount;
displayState(name+" 买 "+buffer);
notify();
return buffer;
}
public void displayState(String operation)
{
StringBuffer outputLine=new StringBuffer(operation);
outputLine.setLength(40);
outputLine.append(buffer+"\t\t"+occupiedBufferCount);
System.out.println(outputLine);
System.out.println();
}
}
class Producer extends Thread
{
private Buffer sharedLocation;
public Producer(Buffer shared)
{
super("Producer");
sharedLocation=shared;
}
public void run()
{
for(int count=1;count<=4;count++)
{
try
{
Thread.sleep((int)(Math.random()*3001));
sharedLocation.set(count);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(getName()+" 生产结束");
}
}

class Consumer extends Thread
{
private Buffer sharedLocation;
public Consumer(Buffer shared)
{
super("Consumer");
sharedLocation=shared;
}
public void run()
{
int sum=0;
for(int count=1;count<=4;count++)
{
try
{
Thread.sleep((int)(Math.random()*3001));
sum+=sharedLocation.get();

}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(getName()+" 消费总数 "+sum+" 消费结束");

}
}

搜索更多相关主题的帖子: 开源 经典 实例 线程 JAVA 
2007-05-04 21:08



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-136917-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012817 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved