通过join方法顺序执行多个线程
方法一:直接用多线程之间的通讯去解决
package com.toov5.test;
import javax.imageio.ImageTypeSpecifier;
class Res1{
char flag = 'A' ;
}
class A extends Thread{
Res1 res;
public A(Res1 res) {
this.res=res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
if (res.flag == 'A') {
System.out.println("A");
res.flag='B';
res.notifyAll();
}else {
try {
res.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
class B extends Thread{
Res1 res;
public B(Res1 res) {
this.res=res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
if (res.flag == 'B') {
System.out.println("B");
res.flag='C';
res.notifyAll();
}else {
try {
res.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
class C extends Thread{
Res1 res;
public C(Res1 res) {
this.res=res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
if (res.flag == 'C') {
System.out.println("C");
res.flag='D';
}else {
try {
res.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class Test9 {
public static void main(String[] args) {
Res1 res1 = new Res1();
A a = new A(res1);
B b = new B(res1);
C c = new C(res1);
a.start();
b.start();
c.start();
}
}
方法二:join()去执行
public class JoinThreadDemo02 {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println("A");
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
t1.join();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("B");
}
});
Thread t3 = new Thread(new Runnable() {
public void run() {
try {
t2.join();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("C");
}
});
t1.start();
t2.start();
t3.start();
}
}
解读:三个线程在交替执行,被cpu去调度。 如果调度的是t3 那么执行的是 t2.join() 此时t2线程又是跑了 t1.join(),一次类推、
总之 三个线程去调度时候 都是不确定的 每次的调度都是套着环在里面 每种可能性都有了设计
我喜欢这样的代码