您的位置:首页 > 其它

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

2015-07-04 16:31 387 查看
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();

}

}

希望大家赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: