public class Banyungong implements Runnable {
private Computer computer = null;
public Banyungong(Computer computer) {
this.computer = computer;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
computer.get();
}
}
}
package com.xmjr.test;
public class Computer {
private String shubiao = "shubiaoA";
private String zhuji = "zhujiA";
private String jianpan = "jianpanA";
private boolean flag = false;
public synchronized void get() {
if (flag) {
try {
super.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getZhuji() + "-->" + getShubiao() + "-->" + jianpan);
flag = true;
super.notify();
}
/**
* @return the jianpan
*/
public String getJianpan() {
return jianpan;
}
/**
* @return the shubiao
*/
public String getShubiao() {
return shubiao;
}
/**
* @return the zhuji
*/
public String getZhuji() {
return zhuji;
}
public synchronized void set(String shubiao, String jianpan, String zhuji) {
if (!flag) {
try {
super.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
setJianpan(jianpan);
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
setShubiao(shubiao);
setZhuji(zhuji);
flag = false;
super.notify();
}
/**
* @param jianpan
* the jianpan to set
*/
public void setJianpan(String jianpan) {
this.jianpan = jianpan;
}
/**
* @param shubiao
* the shubiao to set
*/
public void setShubiao(String shubiao) {
this.shubiao = shubiao;
}
/**
* @param zhuji
* the zhuji to set
*/
public void setZhuji(String zhuji) {
this.zhuji = zhuji;
}
}
package com.xmjr.test;
public class Maker implements Runnable {
private Computer computer = null;
public Maker(Computer computer) {
this.computer = computer;
}
@Override
public void run() {
boolean b = false;
for (int i = 0; i < 50; i++) {
if (b) {
computer.set("鼠标a" + i, "键盘a" + i, "主机a" + i);
b = false;
} else {
computer.set("鼠标b" + i, "键盘b" + i, "主机b" + i);
b = true;
}
}
}
}
package com.xmjr.test;
public class Test {
public static void main(String[] args) {
Computer computer = new Computer();
Maker maker = new Maker(computer);
Banyungong ban = new Banyungong(computer);
Thread threadMaker = new Thread(maker);
Thread threadBan = new Thread(ban);
threadMaker.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadBan.start();
}
}