首页 > 编程语言 > 详细

线程通讯和线程安全实例

时间:2015-12-27 13:20:25      阅读:173      评论:0      收藏:0      [点我收藏+]

 

 

 

 

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();
    }

}

 




线程通讯和线程安全实例

原文:http://www.cnblogs.com/loadstar/p/5079856.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!