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

📄 java.txt

📁 生产者与消费者的问题
💻 TXT
字号:
/*  TestThreads.java */ 

// The main App : class TestThreads
// The synchronized resource: class SynSource
// The Productor: class Productor 
// The Customer: class Customer 

class TestThreads
{
    public static void main(String []args)
    {
        SynSource resource = new SynSource();
        // 启动2个product 线程 和 2个 customer线程 对 线程安全的 SynSource 进行操作 
        new Thread(new Productor(resource)).start();
        new Thread(new Productor(resource)).start();
        new Thread(new Customer(resource)).start();
        new Thread(new Customer(resource)).start();
    }
}

// The most important thinsg 
class SynSource
{
    // 长度为10的列表 
    private ArrayList source = new ArrayList(10); 
    
    // 生产
    public synchronized void push(char in)
    {
         if(source.size()<10)
         {
              source.add(new Character(in));
              this.notify(); 
         }
         else
         {
              try{this.wait();}catch(Exception e){}
         }
     } 

    // 消费
    public synchronized char pop()
    {
         if(!source.isEmpty())
         {
              char tmp = ((Character)source.get(source.size()-1)).charValue();
              source.remove(source.size()-1);
              this.notify(); 
              return tmp;
         }
         else
         {
             try{this.wait();}catch(Exception e){}
         }
    }
} 

// 生产者进程 
class Product implements Runnalbe 
{
    private SynSource source;
    private int productID;
    private static int productNum = 1;

    public Product(SynSource source)
    {
        this.source = source;
        productID = productNum ++;
    }
   
    public void run() 
    {
        while(true)
        {
             char tmp = (char)(Math.Random()*26 + 'A');
             System.out.println("Product id" + productID  + ": " + tmp);
             source.push(tmp);
             Thread.sleep(300); 
        }
    }
} 

// 消费者进程 
public Customer implements Runnalbe 
{
    private SynSource source;
    private int customerID;
    private static int customerNum =1;

    public Customer(SynSource source)
    {
        this.source = source;
        customerID = customerNum ++;
    }
    
    public void run() 
    {
        while(true)
        {
             char tmp = source.pop();
             System.out.println("Customerid" + customerID+ ": " + tmp);
             Thread.sleep(300);
        }
    }
}

⌨️ 快捷键说明

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