码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程的交替执行

时间:2014-11-17 17:50:48      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:java   多线程   thread   

      读完Think In Java的多线程,深有感悟,花了1个小时,写了一个多线程交替执行程序,大家可以参考,如有好的意见,请提出,谢谢!

package com.thread;


public class ThreadTest implements Runnable {



public void run() {
int j = 0;
while (true) {

try {
synchronized (this) {
if (j == 5) {
j = 0;
Tmp.getA().setOnoff(true);
Tmp.getA().Notify();
wait();
}
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("XX+++"+j);
j++;
}
}




public synchronized void Notify() {
notify();
}

public static void main(String[] args) {

ThreadA A = new ThreadA();
Thread testA = new Thread(A);
testA.start();

ThreadTest B = new ThreadTest();
Thread testB = new Thread(B);
testB.start();

Tmp tmp = new Tmp();
tmp.setB(B);
tmp.setA(A);


}


}


class Tmp {
private static ThreadTest B;
private static ThreadA A;

public static ThreadA getA() {
return A;
}


public static void setA(ThreadA a) {
A = a;
}


public static ThreadTest getB() {
return B;
}


public static void setB(ThreadTest b) {
B = b;
}
}


class ThreadA implements Runnable {


boolean Onoff = false;


public boolean setOnoff(boolean LnKai) {
return Onoff = LnKai;
}


public synchronized void Notify() {
notify();
}



public void run() {
int j = 0;
while (true) {

while (Onoff) {

try {
synchronized (this) {
if (j == 5) {
j=0;
Onoff = false;
Tmp.getB().Notify();
wait();
}
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("YY---"+j);
j++;

}
}


}
}

结果:

XX+++0
XX+++1
XX+++2
XX+++3
XX+++4
YY---0
YY---1
YY---2
YY---3
YY---4
XX+++0
XX+++1
XX+++2
XX+++3
XX+++4
YY---0
YY---1
YY---2
YY---3
YY---4
XX+++0
XX+++1
XX+++2
XX+++3
XX+++4
YY---0
YY---1
YY---2
YY---3
YY---4

Java多线程的交替执行

标签:java   多线程   thread   

原文地址:http://blog.csdn.net/longhua2014/article/details/41211797

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!