static Semaphore semaphore1 =newSemaphore(1);static Semaphore semaphore2 =newSemaphore(1);static Semaphore semaphore3 =newSemaphore(1);publicstaticvoidmain(String[] args){try{
semaphore2.acquire();
semaphore3.acquire();}catch(InterruptedException e){
e.printStackTrace();}newThread(()->{for(int i =0; i <10; i++){try{
semaphore1.acquire();
System.out.print("A");}catch(InterruptedException e){
e.printStackTrace();}finally{
semaphore2.release();}}}).start();newThread(()->{for(int i =0; i <10; i++){try{
semaphore2.acquire();
System.out.print("B");}catch(InterruptedException e){
e.printStackTrace();}finally{
semaphore3.release();}}}).start();newThread(()->{for(int i =0; i <10; i++){try{
semaphore3.acquire();
System.out.println("C");}catch(InterruptedException e){
e.printStackTrace();}finally{
semaphore1.release();}}}).start();}
一、使用ReentrantLock
classMyThreadextendsThread{privatestaticint state =1;privatestatic Lock lock =newReentrantLock();@Overridepublicvoidrun(){
lock.lock();try{for(int i =0; i <10;){if(state%3==1){
System.out.print("A");
state++;
i++;}elseif(state%3==2){
System.out.print("B");
state++;
i++;}else{
System.out.println("C");
state++;
i++;}}}catch(Exception e){
e.printStackTrace();}finally{
lock.unlock();}}}publicclassABC{publicstaticvoidmain(String[] args){newMyThread().start();newMyThread().start();newMyThread().start();}}
三、使用synchronized
publicclassABC3{publicstaticvoidmain(String[] args){
MyPrint myPrint =newMyPrint();newThread(()->{for(int i =0; i <100;){if(myPrint.getState()%3==1){
System.out.print(Thread.currentThread().getName());
myPrint.increment();
i++;}}},"A").start();newThread(()->{for(int i =0; i <100;){if(myPrint.getState()%3==2){
System.out.print(Thread.currentThread().getName());
myPrint.increment();
i++;}}},"B").start();newThread(()->{for(int i =0; i <100;){if(myPrint.getState()%3==0){
System.out.println(Thread.currentThread().getName());
myPrint.increment();
i++;}}},"C").start();}}classMyPrint{privateint state =1;publicsynchronizedvoidincrement(){
state++;}publicintgetState(){returnthis.state;}}