test1.java

来自「实例精华」· Java 代码 · 共 121 行

JAVA
121
字号
public class Test1
{
	
	public static void main(String[] args)
	{
		Hollow h = new Hollow();
		Producer p = new Producer(h);
		Consumer c = new Consumer(h);
		p.start();
		c.start();
		
	}
}

class Producer extends Thread
{
	
	Hollow h;
	
	public Producer(Hollow h)
	{
		
		this.h=h;
	}
	public void run()
	{
		
		for (int i = 0; i<10; i++)
		{
			
			h.put(i);
			
			System.out.println("put:"+i);
			
		}
	}
	
}

class Hollow
{
	
	int value;
	boolean flag=false;

	//当方法中使用了wait() notify()方法时,此方法需要用synchronized来修饰
	public synchronized void put(int value)
	{
		    if(!flag)
		    {
		    	
		    	this.value=value;
		    	
		    	flag=true;
		    	
		    	notify();
		    }
		    
		    try {
		    	
		    	wait();
		    }
		    catch (Exception ex) {
		    	
		    	
		    	ex.printStackTrace();
		    }
		    
            
			

		
	}
	
	public synchronized int get()
	{
		    if(!flag)
		    {
		    	try {
		    		
		    		wait();
			    }
			    catch (Exception ex) {
			    	
			    	
			    	ex.printStackTrace();
			    }
		    	
		    }
		    flag=false;
		    
		    notify();

		    return this.value;

	}
	
}

class Consumer extends Thread
{
	
	Hollow h;
	
	public Consumer(Hollow h)
	{
		
		this.h=h;
	}
	
	public void run()
	{
		
       while(true)
       
        System.out.println("get:"+h.get()); 		
		
	}
	
	
}

⌨️ 快捷键说明

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