欢迎来到虫虫下载站 | 资源下载 资源专辑 关于我们
虫虫下载站

prdcons.java

有关java的源程序,为讲授java程序设计课程使用
JAVA
字号:
import java.io.*;
import java.applet.*;
class Producer extends Thread
{
	private Box box;
	public Producer(Box box)
	{
		this.box=box;
	}
	public void run()
	{
		for(int i=0;i<10;i++)
		{
			box.put(i);
			System.out.println("Producer put:"+i);
			try
			{
				sleep((int)(Math.random()*100));
			}
			catch(InterruptedException e) {	}
		}
	}
}
class Consumer extends Thread
{
	private Box box;
	public Consumer(Box box)
	{
		this.box=box;
	}
	public void run()
	{
		int value;
		for(int i=0;i<10;i++)
		{ value=box.get();
		  System.out.println("Consumer got:"+value);
		}
	}
}
class Box
{
	private int contents;
	public int get()
	{  
	    return contents;
	}
	public synchronized void put(int value)
	{  
	    contents=value;
	}
}
public class  PrdCons 
{
	public static void main(String args[])
	{Box b=new Box();
	Producer p=new Producer(b);
	Consumer c=new Consumer(b);
	p.start();
	c.start();
		try
		{
			System.in.read();
		}catch(IOException e)
		{
		}
	}
}

⌨️ 快捷键说明

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