📄 communicationdemo2.java
字号:
// 例4.6.2 CommunicationDemo2.java
class SyncStack // 同步堆栈类,可以一次放入多个数据
{
private int index = 0; // 堆栈指针初始值为0
private char[] buffer = new char[5]; // 堆栈有5个字符的空间
public synchronized void push(char c) // 入栈同步方法
{
if(index == buffer.length) // 堆栈已满,不能入栈
{
try
{
this.wait(); //等待出栈线程将数据出栈
}catch(InterruptedException e){ }
}
buffer[index] = c; // 数据入栈
index++; // 指针加1,栈内空间减少
this.notify(); // 通知其它线程把数据出栈
}
public synchronized char pop() // 出栈同步方法
{
if(index == 0) // 堆栈无数据,不能出栈
{
try
{
this.wait(); //等待入栈线程把数据入栈
}catch(InterruptedException e){ }
}
this.notify(); //通知其它线程入栈
index--; //指针向下移动
return buffer[index]; //数据出栈
}
}
class Producer implements Runnable //生产者类
{
SyncStack s; //生产者类生成的字母都保存到同步堆栈中
public Producer(SyncStack s)
{
this.s = s;
}
public void run()
{
char ch;
for(int i=0; i<5; i++)
{
try
{
Thread.sleep((int)(Math.random()*1000)); }catch(InterruptedException e){ }
ch =(char)(Math.random()*26+'A'); //随机产生5个字符
s.push(ch); //把字符入栈
System.out.println("Push "+ch+" in Stack"); // 打印字符入栈
}
}
}
class Consumer implements Runnable //消费者类
{
SyncStack s; //消费者类获得的字符都来自同步堆栈
public Consumer(SyncStack s)
{
this.s = s;
}
public void run()
{
char ch;
for(int i=0;i<5;i++)
{
try
{
Thread.sleep((int)(Math.random()*3000));
}catch(InterruptedException e){ }
ch = s.pop(); //从堆栈中读取字符
System.out.println("Pop "+ch+" from Stack"); //打印字符出栈
}
}
}
public class CommunicationDemo2
{
public static void main(String[] args)
{
SyncStack stack = new SyncStack();
//下面的消费者类对象和生产者类对象所操作的是同一个同步堆栈对象
Thread t1 = new Thread(new Producer(stack)); //线程实例化
Thread t2 = new Thread(new Consumer(stack)); //线程实例化
t2.start(); //线程启动
t1.start(); //线程启动
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -