栈的先进后出的算法演示程序,欢迎讨论
/*栈的先进后出的算法演示程序,请各位大侠指教。*/
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();
}
}
}