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