日期:2014-05-20 浏览次数:20737 次
public class Consumer implements Runnable{
private Info info;
public Consumer(Info info){
this.info = info;}
public void run() {
for(int i=0;i<50;i++){
this.info.get();
}}}
public class Producer implements Runnable {
private Info info = null;
public Producer(Info info){
this.info = info;}
public void run() {
boolean flag = false;
for(int i=0;i<50;i++){
if(!flag){
this.info.set("xielongtao", "basketball");
flag = true;
}else{
this.info.set("谢龙涛","篮球");
flag = false;}}}}
public class Info {
private String name = "谢龙涛";
private String hobby = "篮球";
private boolean flag = false;
public String getName() {
return name;}
public void setName(String name) {
this.name = name;}
public String getHobby() {
return hobby;}
public void setHobby(String hobby) {
this.hobby = hobby;}
public synchronized void set(String name,String hobby){
System.out.println(Thread.currentThread().getName()+"set");
if (!flag) {
try {
this.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
this.setName(name);
this.setHobby(hobby);
flag = false;
super.notify(); }}
public synchronized void get(){
System.out.println(Thread.currentThread().getName()+"get");
if (flag) {
try {
this.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("name:" + this.getName() + " hobby:"
+ this.getHobby());
flag = true;
super.notify();}}}
public class SycronizeTest {
public static void main(String[] args) {
Info info = new Info();
Consumer c = new Consumer(info);
Producer p = new Producer(info);
new Thread(c,"consumer").start();
new Thread(p,"producer").start();}}
public synchronized void set(String name,String hobby){
System.out.println(Thread.currentThread().getName()+"set");
if (!flag) {// 表示是满的 不能加
try {
this.wait();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.setName(name);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//-------------------------------if 在此结束
this.setHobby(hobby);
flag = false;//让他取
super.notify();
//}// -------------------------------这不要