public class MultiThread implements Runnable {
private static volatile String msg = "线程一打印A"; //volatile用来保证静态变量的修改对其他线程都是可见的。不加运行测试也可以,最好加上。
private String message;
private String next;
public MultiThread(String message, String next) {
this.message = message;
this.next = next;
}
public static void main(String[] args) {
//先创建runnable实现类对象, 然后创建thread类对象,将runnable实现类对象作为实参传递。
new Thread(new MultiThread("线程一打印A", "线程二打印B")).start();
new Thread(new MultiThread("线程二打印B", "线程三打印C")).start();
new Thread(new MultiThread("线程三打印C", "线程一打印A")).start();
}
//实现run方法,将自定义线程的任务定义在run方法上
public void run() {
for(int i = 0; i < 10;) {
if(this.message.equals(MultiThread.msg)) {
System.out.println(this.message);
MultiThread.msg = next;
i++;
}
}
}
}
输出结果
线程一打印A
线程二打印B
线程三打印C
线程一打印A
线程二打印B
线程三打印C
线程一打印A
线程二打印B
线程三打印C
线程一打印A
线程二打印B
线程三打印C
线程一打印A
线程二打印B
线程三打印C
线程一打印A
线程二打印B
线程三打印C
线程一打印A
线程二打印B
线程三打印C
线程一打印A
线程二打印B
线程三打印C
线程一打印A
线程二打印B
线程三打印C
线程一打印A
线程二打印B
线程三打印C