public class Test implements Runnable {
private static volatile String msg = "线程一打印A";
private String message;
private String next;
public Test(String message, String next) {
this.message = message;
this.next = next;
}
public static void main(String[] args) {
new Thread(new Test("线程一打印A", "线程二打印B")).start();
new Thread(new Test("线程二打印B", "线程三打印C")).start();
new Thread(new Test("线程三打印C", "线程一打印A")).start();
}
public void run() {
for(int i = 0; i < 10;) {
if(this.message.equals(Test.msg)) {
System.out.println(this.message);
Test.msg = next;
i++;
}
}
}
}
这样写不需要同步代码, 应该会更自然点