package 多线程;
public class ThreadcommunicateSafe1 {
public static void main(String[] args) {
Info3 mess= new Info3();
Input3 in = new Input3(mess);
Output3 out = new Output3(mess);
new Thread(in).start();
new Thread(out).start();
}
}
//1,等待唤醒机制 实现 Input线程和Output线程交替获取执行全交替复活执行
class Info3{
private String name;
private String sex;
private boolean flag;
public synchronized void set(String name,String sex){
if(flag)
try {
this.wait();
this.name = name;
this.sex = sex;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
flag=false;
this.notify();
}
public synchronized void sop(){
if(!flag)
try {
this.wait();
System.out.println(Thread.currentThread().getName()+"名字:"+name+"。。。。__性别:"+sex);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = true;
this.notify();
}
}
class Input3 implements Runnable{
Info3 info;
int x = 0;
public Input3(Info3 info) {
this.info=info;
}
@Override
public void run() {
while (true) {
if (x==0) {
info.set("demo", "man");
} else {
info.set("丽丽", "女生");
}
x=(x+1)%2;
}
}
}
class Output3 implements Runnable{
Info3 info;
public Output3(Info3 info) {
this.info=info;
}
public void run() {
while (true) {
info.sop();
}
}
}
//2,通过创建一个标记flag 让Input线程和Output线程交替执行代码 但是Input线程和Output线程 还是随机获取执行权
//class Info2{
// String name;
// String sex;
// boolean flag;
//}
//class Input2 implements Runnable{
// Info2 info;
// int x = 0;
// public Input2(Info2 info) {
// this.info=info;
// }
// @Override
// public void run() {
// while (true) {
// if(info.flag){
// synchronized(info){
// if (x==0) {
// info.name = "demo";
// info.sex = "man";
// } else {
// info.name = "莉莉";
// info.sex = "女生";
// }
// x=(x+1)%2;
// info.flag=false;
// }
// }
// }
// }
//}
//class Output2 implements Runnable{
// Info2 info;
// public Output2(Info2 info) {
// this.info=info;
// }
// public void run() {
// while (true) {
// if(info.flag==false){
// synchronized(info){
// System.out.println("名字:"+info.name+"__性别:"+info.sex);
// info.flag = true;
// }
// }
//
// }
// }
//}本文出自 “要么拼命,要么滚回去!” 博客,请务必保留此出处http://jiangzuun2014.blog.51cto.com/8732469/1440621
原文:http://jiangzuun2014.blog.51cto.com/8732469/1440621