java--两线程通信
package com.mythread;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class danlie {
public static void main(String[] args) throws InterruptedException {
//extracted_1();
final Printer p =new Printer();
new Thread() {
public void run() {
while (true) {
try {
p.print1();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
while (true) {
try {
p.print2();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
class Printer{
private int flag =1;
Demo d =new Demo();
public synchronized void print1() throws Exception {
//synchronized(d){
if(flag !=1) {
this.wait();
}
System.out.print("test1");
System.out.print("test2");
System.out.print("test3");
System.out.print("test4");
System.out.print("\r\n");
flag =2;
this.notify();
//}
}
public synchronized void print2() throws Exception {
//synchronized(d){
if(flag !=2) {
this.wait();
}
System.out.print("print5");
System.out.print("print6");
System.out.print("print7");
System.out.print("\r\n");
flag =1;
this.notify();
//}
}
}
******************************人因为有理想、梦想而变得伟大,而真正伟大就是不断努力实现理想、梦想*****************************