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

java多线程——线程间的通讯

时间:2015-04-09 08:51:35      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:多线程

public class ThreadDemo3 {
    public static void main(String[] args) {
        Resource res = new Resource();
        Input input = new Input(res);
        Output output = new Output(res);
        Thread t1 = new Thread(input);
        Thread t2 = new Thread(output);

        t1.start();
        t2.start();
    }
}

class Resource {
    String name;
    String gender;
}

class Input implements Runnable {
    Resource res;

    Input(Resource res) {
        this.res = res;
    }
    public void run(){
        int x = 1;
        while (true){
            synchronized (Resource.class) {
                if (x%2 == 0){
                    this.res.name = "Kury";
                    this.res.gender = "male";
                } else {
                    this.res.name = "库里";
                    this.res.gender = "男人";
                }
                x++;
            }           
        }
    }
}

class Output implements Runnable {
    Resource res;
    Output(Resource res){
        this.res = res;
    }

    public void run(){
        while(true){
            synchronized (Resource.class) {
                System.out.println(this.res.name + "------" + this.res.gender);
            }
        }
    }
}

java多线程——线程间的通讯

标签:多线程

原文地址:http://blog.csdn.net/u011402596/article/details/44950033

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!