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

📄 customerandproducter.java

📁 消费者与生产者游戏
💻 JAVA
字号:
import java.io.*;

class Market
{
	int i;
	boolean flag;
	
    public Market()
	{
		i=1;
		flag=false;
	}
	public synchronized void put(int j)
	{		
		i=j;
		if(flag==true)
		{
			try
			{
				wait();
			}
			catch(InterruptedException ie)
			{
				System.out.println(ie);
			}
		}
		System.out.println("put :"+i);
		flag=true;
		notify();
	}
	public synchronized void get()
	{
		if(flag==false)
		{
			try
			{
				wait();
			}
			catch(InterruptedException ie)
			{
				System.out.println(ie);
			}
		}
		System.out.println("Get :"+i);
		flag=false;
		notify();
		
	}
} 

class Producter extends Thread
{
	int k;
	Market m;
	public Producter(Market n)
	{
		k=1;
		m=n;
		Thread t=new Thread(this);
		t.start();
	}
	public void run()
	{
		while(true)
		{
			m.put(k++);
		}
	}
	
}
class Customer extends Thread 
{
	Market m;
	public Customer(Market n)
	{
		m=n;
		Thread t=new Thread(this);
		t.start();
	}
	public void run()
	{
		while(true)
	    { 
		    m.get();
	    }
	}
}
public class CustomerAndProducter 
{
	public static void main(String[] args)
	{
		Market w=new Market();
		new Producter(w);
		new Customer(w);
	}
}

⌨️ 快捷键说明

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