synctest.java

来自「这是一张java应用教程的随书光盘」· Java 代码 · 共 66 行

JAVA
66
字号
class SyncStack{  //支持多线程同步操作的堆栈的实现
	private int index = 0;
	private char []data = new char[6];	
	public synchronized void push(char c){
		while(index == data.length){
		try{
			     this.wait();
			}catch(InterruptedException e){}
	 		}
	 	this.notify();
		data[index] = c;
	 	index++;
	}
	public synchronized char pop(){
		 while(index ==0){
			try{
				this.wait();
			}catch(InterruptedException e){}
  		    	}
		this.notify();
  		index--;
  		return data[index];
	}
}
class  Producer implements Runnable{   //生产者
SyncStack stack;	
public Producer(SyncStack s){
		stack = s;
		}
public void run(){
	    for(int i=0; i<3; i++){
		char c =(char)(Math.random()*26+'A');
		stack.push(c);
		System.out.println("生产:"+c);
		try{							        Thread.sleep((int)(Math.random()*100));
		}catch(InterruptedException e){}
	    }
}
      }
class Consumer implements Runnable{       //消费者
SyncStack stack;	
public Consumer(SyncStack s){
		stack = s;
		}
public void run(){
		for(int i=0;i<3;i++){
			char c = stack.pop();
			System.out.println("消费: "+c);
			try{							           Thread.sleep((int)(Math.random()*1000));
			}catch(InterruptedException e){}
		}
}
	}
public class SyncTest{                 //主程序
	    public static void main(String args[]){
		SyncStack stack = new SyncStack();
		Runnable p=new Producer(stack);
		Runnable c = new Consumer(stack);
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(c);
		t1.start();
		t2.start();
	    }
	}
	

⌨️ 快捷键说明

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