两个线程交叉打印(最简单的)

A:线程:

package Thread.a.b.turn;


public class ThreadA implements Runnable {
private ThreadBusiness treadMian =null;
public ThreadA(ThreadBusiness threadMain ){
this.treadMian=threadMain;
}


public void run() {
// TODO Auto-generated method stub


for(int i=0;i<10;i++){
treadMian.printA();
}
}


}

B线程:

package Thread.a.b.turn;


public class ThreadB implements Runnable {
private ThreadBusiness treadMian =null;
public ThreadB(ThreadBusiness threadMain ){
this.treadMian=threadMain;
}
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
treadMian.printB();
}
}


}

业务逻辑:

package Thread.a.b.turn;


public class ThreadBusiness {
public boolean flag=true;



public synchronized void printA(){
if(!flag){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
flag=false;
System.out.println("A");
notify();
}

public synchronized void printB(){
if(flag){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
flag=true;
System.out.println("B");
notify();
}

}

测试:

package Thread.a.b.turn;


public class TestThreadAB {
public static void main(String args[]){
//先让A线程打印,后让B线程打印
ThreadBusiness threadMain = new ThreadBusiness();
Thread a = new Thread(new ThreadA(threadMain),"A"); 
Thread b = new Thread(new ThreadB(threadMain),"B");
a.start();
b.start();
}
}

希望大家赐教。

你可能感兴趣的:(多线程)