java多线程---顺序打印ABC的三种实现---volatile方式

利用volatile的立即可见性:

package com.zcj.thread; public class PrintABC2 { private volatile int status =1; public void printA(){ while(status!=1){} System.out.print("A"); status=2; } public void printB(){ while(status!=2){} System.out.print("B"); status=3; } public void printC(){ while(status!=3){} System.out.println("C"); status=1; } public static void main(String[] args){ PrintABC2 print = new PrintABC2(); Thread threadA = new Thread(new RunnableA2(print)); Thread threadB = new Thread(new RunnableB2(print)); Thread threadC = new Thread(new RunnableC2(print)); threadA.start(); threadB.start(); threadC.start(); } }class RunnableA2 implements Runnable{ private PrintABC2 print; public RunnableA2(PrintABC2 print) { super(); this.print = print; } @Override public void run() { // TODO Auto-generated method stub for(int i=0; i<10; i++){ print.printA(); } } } class RunnableB2 implements Runnable{ private PrintABC2 print; public RunnableB2(PrintABC2 print) { super(); this.print = print; } @Override public void run() { // TODO Auto-generated method stub for(int i=0; i<10; i++){ print.printB(); } } } class RunnableC2 implements Runnable{ private PrintABC2 print; public RunnableC2(PrintABC2 print) { super(); this.print = print; } @Override public void run() { // TODO Auto-generated method stub for(int i=0; i<10; i++){ print.printC(); } } }



【java多线程---顺序打印ABC的三种实现---volatile方式】

    推荐阅读