public class ThreadcommunicateSafe { public static void main(String[] args) { Info mess= new Info(); Input in = new Input(mess); Output out = new Output(mess); new Thread(in).start(); new Thread(out).start(); } } class Info{ String name; String sex; } class Input implements Runnable{ Info info; int x = 0; public Input(Info info) { this.info=info; } @Override public void run() { while (true) { synchronized(info){ if (x==0) { info.name = "demo"; info.sex = "man"; } else { info.name = "莉莉"; info.sex = "女生"; } x=(x+1)%2; } } } } class Output implements Runnable{ Info info; public Output(Info info) { this.info=info; } public void run() { while (true) { synchronized(info){ System.out.println("名字:"+info.name+"__性别:"+info.sex); } } } } /* * 输出 名字:莉莉__性别:女生 名字:莉莉__性别:女生 名字:莉莉__性别:女生 名字:莉莉__性别:女生 名字:demo__性别:man 名字:demo__性别:man 名字:demo__性别:man 名字:demo__性别:man 名字:demo__性别:man 名字:demo__性别:man 名字:demo__性别:man */
本文出自 “要么拼命,要么滚回去!” 博客,请务必保留此出处http://jiangzuun2014.blog.51cto.com/8732469/1440600
原文地址:http://jiangzuun2014.blog.51cto.com/8732469/1440600