java多线程例子(生成者和消费者)

Info.cs 商品

public class Info {
    boolean flag=false;
    private String name="张三";
    private int age=30;    
    public synchronized void set(String name,int age)
    {
        try
        {
            if(!flag)            
                super.wait();            
        }
        catch(InterruptedException ex)
        {
            System.out.println(ex.getStackTrace());
        }
        
        try
        {        
            this.name=name;
            Thread.sleep(100);
            this.age=age;
        }
        catch(InterruptedException ex)
        {
            System.out.println(ex.getStackTrace());
        }
        flag=false;
        super.notify(); //唤醒调用了wait的方法线程
    }
    public synchronized void get()
    {
        try
        {
            if(flag)
                super.wait();
        }
        catch (InterruptedException ex)
        {
            System.out.println(ex.getStackTrace());
        }
        try
        {
            Thread.sleep(100);
            System.out.println("name:"+name+" age:"+age);
        }
        catch(InterruptedException ex)
        {
            System.out.println(ex.getStackTrace());
        }
        flag=true;
        super.notify();
    }
}

Producter.cs 生产者类

public class Producter implements Runnable{
    Info info=null;
    boolean flag=false;
    final int count=20;
    public Producter(Info info)
    {
        this.info=info;
    }
    public void run()
    {
        for(int i=0;i<count;i++)
        {            
            if(flag)
            {
                this.info.set("张三",30);                
                flag=false;
            }
            else 
            {
                this.info.set("李四",40);
                flag=true;
            }        
            
        }
    }
}

Customer.cs 消费者类

public class Customer implements Runnable{
    Info info;
    final int count=20;
    public Customer(Info info)
    {
        this.info=info;
    }
    public void run()
    {
        for(int i=0;i<count;i++)
        {
            info.get();
        }
    }
}

TestThread.cs 主类

public class TeshThread {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Info info=new Info();
        Producter p=new Producter(info);
        Customer c=new Customer(info);
        new Thread(p).start();
        new Thread(c).start();
    }
}

运行结果:

name:张三 age:30
name:李四 age:40
name:张三 age:30
name:李四 age:40
name:张三 age:30
name:李四 age:40
name:张三 age:30
name:李四 age:40
name:张三 age:30
name:李四 age:40
name:张三 age:30
name:李四 age:40
name:张三 age:30
name:李四 age:40
name:张三 age:30
name:李四 age:40
name:张三 age:30
name:李四 age:40
name:张三 age:30
name:李四 age:40

java多线程例子(生成者和消费者)

上一篇:Chapter 1 Unix System Overview


下一篇:"unable to load dynamic library"错误的解决方法