stacktest.java

来自「Java语言是目前最流行」· Java 代码 · 共 103 行

JAVA
103
字号
//多线程同步
//JAVA使用synchronized关键字来标志被同步的资源
class stack//
{
	int sip = 0;
	String data[] = new String[6];
	public synchronized void push(String str)//标志同步
	{
		while(sip==data.length)
		{
			try
			{
				this.wait();
			}	
			catch(InterruptedException e) 
			{  }
		}	
		this.notify();//通报
		data[sip]=str;
		sip++;
	}
	public synchronized String pop()//标志同步
	{
		while(sip==0)
		{
			try
			{
				this.wait();	
			}	
			catch(InterruptedException e)
			{  }
		}	
		this.notify();//通报
		sip--;
		return data[sip];
	}
}
class Producer implements Runnable
{
	stack stackOne;
	public Producer(stack s)
	{
		stackOne=s;	
	}	
	public void run()
	{
		String strTemp=null;
		for(int i=0;i<8;i++)
		{
			strTemp=String.valueOf(i+1);
			stackOne.push(strTemp);
			System.out.println("Produced:"+strTemp);
			try
			{
				Thread.sleep((int)(Math.random()*100));	//选取随机数进行休眠
			}	
			catch(InterruptedException e)
			{  }
		}	
	}
}
class Consumer implements Runnable
{
	stack stackOne;
	public Consumer(stack s)
	{
		stackOne=s;	
	}	
	public void run()
	{
		String strTemp=null;
		for(int i=0;i<8;i++)
		{
			strTemp=stackOne.pop();
			System.out.println("Consumed:"+strTemp);
			try
			{
				Thread.sleep((int)(Math.random()*100));	
			}	
			catch(InterruptedException e)
			{  }
		}	
	}
}
public class stackTest
{
	public static void main(String[] args)
	{
		stack s1 = new stack();
		Runnable producer = new Producer(s1);
		Runnable consumer = new Consumer(s1);
		Thread p = new Thread(producer);
		Thread c = new Thread(consumer);
		p.start();
		c.start();	
	}	
}
/*
	自定义了一个stack类,不但对堆栈进行了synchronized处理,而且为了协调push()
	和pop()操作,调用了wait()和notify()方法。即当堆栈为满时进行push()
	操作或堆栈为空时进行pop()操作,这时就调用了wait()方法,使当前线城
	暂时释放对堆栈的互斥锁并进入等待队列。
*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?