class Info{
private String name;
private String content;
private boolean flag=false;
public synchronized void set(String name,String content){
this.setName(name);
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
this.setContent(content);
flag=true;
}
public synchronized void get(){
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(this.getName()+"--->"+this.getContent());
flag=false;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
public void setContent(String content){
this.content=content;
}
public String getContent(){
return this.content;
}
}
class Producer implements Runnable{
private boolean flag=false;
private Info info;
public Producer(Info info){
this.info=info;
}
public void run(){
for(int i=0;i<50;i++){
if(flag){
this.info.set("Tom","JAVA讲师");
flag=false;
}else{
this.info.set("Jack","C++讲师");
flag=true;
}
}
}
}
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();
}
}
}
class ThreadTest_02{
public static void main(String[] args){
Info info=new Info();
Producer p=new Producer(info);
Consumer c=new Consumer(info);
new Thread(p).start();
new Thread(c).start();
}
}
这里我想实现 Tom --> java讲师 和Jack --> C++讲师 这两个一样输出一句,怎么实现啊。?
它上面好像就只能 阵输出 Tom --> java讲师 , 要不然就是一阵输出 Jack --> C++讲师。。 |