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();
//}
}

}

你可能感兴趣的:(java--两线程通信)