⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 synctest.java

📁 接着上次传入一些Java学习中的实验
💻 JAVA
字号:
//this java is only the yield() of the all process.
package problem;
public class SyncTest{							//定义一个类。
	public static void main(String args[]) 
	 {
	 	Stack stack=new Stack("stack1");		//produce a class object.
	 	
	 	Producer producer1=new Producer (stack,"producer1"); //produce a class object.
	 	
	 	Consumer consumer1=new Consumer(stack,"consumer1"); //produce a class object.
	 	
	 }
}

class Producer extends Thread{								//extends a thread class use for Producer
	private Stack theStack;									//a class Stack object.
	public  Producer(Stack s,String name){					//a strator for the class
		super(name);
		theStack=s;
		start();
	}
	

public void run(){											
	String goods;
	for(int i=0;i<200;i++)
	 {
	 	goods="goods "+(theStack.getPoint()+1);
	 	theStack.push(goods);
	 	System.out.println(getName()+":push "+goods+"  to: "+theStack.getName());
	 	yield();		
	 	
	 }
  }
}
class Consumer extends Thread{
	 private Stack theStack;
	 public Consumer(Stack s ,String name){
	 	super(name);
	 	theStack=s;
	 	start();
	 	
	 }
	 public void run(){
   		String goods;
   		for(int i=0;i<200;i++){
   		
   		 goods=theStack.pop();
   		 System.out.println(getName()+":pop "+goods+" from: "+theStack.getName());
   		 yield();
   		 }
   	}
}
class Stack{
	private String name;
	private String[] buffer=new String[100];
	
	int point=1;
	public Stack(String name){this.name=name;}
	public String getName(){return name;}
	
	public int getPoint(){return point;}
	
	
	
	public String pop(){
	synchronized(this){	String goods =buffer[point];
		buffer[point]=null;
		Thread.yield();
		point--;
		return goods;
	}
	}
	public void push(String goods)
	 {
	 	point++;
	 	Thread.yield();
	 	buffer[point]=goods;
	 }
	
	
	}

⌨️ 快捷键说明

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