码迷,mamicode.com
首页 > 编程语言 > 详细

线程通讯和线程安全实例

时间:2015-12-27 13:22:19      阅读:158      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!