栈的先进后出的算法演示程序,欢迎讨论

ysycrazy 2006-03-29 03:08:25
/*栈的先进后出的算法演示程序,请各位大侠指教。*/
public class ThreadTest
{
public static void main(String[] args)
{
//从命令行参数中获得该栈的大小
MyStack st = new MyStack(new Integer(args[0]).intValue());
new Thread(new Producer(st)).start();
new Thread(new Customer(st)).start();
}

}
class MyStack //栈
{
char[] data ;
private int index = 0;
private boolean bFull = false;
public MyStack(int size)
{
data = new char[size];
}
public synchronized void pushData(char c) //往栈中推数据
{
if (bFull)
{
try{this.wait();}catch(Exception e){};
}
data[index]=c;
try
{
Thread.sleep(300);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
index++;
System.out.println("把字符\'"+c+"\'推入栈中");
if (index == data.length)
{
bFull = true;
}
if (bFull)
{
this.notify();
}
}
public synchronized char popData() //从栈中取数据
{
if (!bFull)
{
try{this.wait();}catch(Exception e){e.printStackTrace();};
}
char c;
index--;
try
{
Thread.sleep(300);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
c=data[index];
System.out.println("从栈中取出字符\'"+c+"\'");
if (index==0)
{
bFull = false;
}
if (!bFull)
{
this.notify();
}
return c;
}
}

class Producer implements Runnable
{
MyStack st;
public Producer(MyStack st)
{
this.st=st;
}
public void run()
{
while (true)
{
st.pushData((char)(Math.random() * 26 + 'A'));

}
}
}
class Customer implements Runnable
{
MyStack st;
public Customer(MyStack st)
{
this.st=st;
}
public void run()
{
while (true)
{
st.popData();
}
}
}
...全文
218 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧