线程通讯和线程安全实例

 

 

 

 

package com.xiaoju.demo;

/**
 * Hello world!
 * Thread Communication and Thread safe Sample!!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        // Thread Communication
        Q q = new Q();
        new Thread(new Producer(q)).start();
        new Thread(new Consumer(q)).start();

    }
}

class Producer implements Runnable{
    Q q;
    public Producer(Q q){
        this.q=q;
    }
    public void run(){
        int i=0;
        while (true){
            if(i==0){
                q.put("zhangsan","male");
            }
            else {
                q.put("lisi","female");
            }
            i=(i+1)%2;
        }
    }
}

class Consumer implements Runnable{
    Q q;
    public Consumer(Q q)
    {
        this.q=q;
    }
    public void run(){
        while (true){
            q.get();
        }
    }
}

class Q{
    private String name="unknown";
    private String sex="unknown";
    private boolean bFull=false;
    public synchronized void put(String name,String sex){
        if(bFull) {
            try {
                wait();
            } catch (Exception e) {
            }
        }

        this.name=name;
        try{Thread.sleep(1);}catch (Exception e) {}
        this.sex=sex;
        bFull=true;
        notify();
    }

    public synchronized void get(){
        if(!bFull)
        {
            try{wait();} catch (Exception e) {}
        }

        System.out.print(name);
        System.out.println(":"+sex);
        bFull=false;
        notify();
    }

}

 




posted @ 2015-12-27 12:26  loadstar  阅读(139)  评论(0)    收藏  举报