Java线程间通信的简单例题

两个线程循环顺序打印A、B 需求:两个线程循环顺序打印A、B 思路:1.通过匿名内部类创建两个线程 2.重写Run方法,循环打印 3.定义方法printA,线程间通信当flag=0时打印A 4.定义方法printB,线程间通信当flag=1时打印B

首先定义一个类,获取和存放flag的true或false

package ch09;

public class Xunhuan {
   private boolean flag;
   public boolean isFlag() {
   	return flag;
   }

   public void setFlag(boolean flag) {
   	this.flag = flag;
   }
   
}

定义循环ab类,在类下创建主函数,以及继承Thread的两个内部XunhuanA和XunhuanB类。

package ch09;

public class Xunhuanab {
	public static void main(String[] args) {
		Xunhuan x = new Xunhuan();
		x.setFlag(false);
		Thread a = new XunhuanA(x);
		Thread b = new XunhuanB(x);
		a.start();
		b.start();
	}
}

class XunhuanA extends Thread {
	private Xunhuan x;

	public XunhuanA(Xunhuan x) {
		this.x = x;
		// TODO Auto-generated constructor stub
	}

	@Override
	public void run() {
		synchronized (x) {

			for (int i = 1; i <= 10; i++) {
				while(x.isFlag()==true) {
					try {
						x.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}


				}		
				System.out.println("A");
				x.setFlag(true);
				x.notify();
			}
			// TODO Auto-generated method stub
		}
	}
}

class XunhuanB extends Thread {
	private Xunhuan x;

	public XunhuanB(Xunhuan x) {
		this.x = x;
		// TODO Auto-generated constructor stub
	}

	@Override
	public void run() {
		synchronized (x) {

			for (int j = 1; j <= 10; j++) {
				while(x.isFlag()==false) {
					try {
						x.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}


				}		
				System.out.println("B");
				x.setFlag(false);
				x.notify();
			}

		}
		// TODO Auto-generated method stub
	}
}

你可能感兴趣的:(java多线程,java基础,java)