首页 > 代码库 > Java多线程的交替执行
Java多线程的交替执行
读完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多线程的交替执行