三线程连续打印ABC

 1 package test5;
 2 
 3 import java.util.concurrent.locks.Condition;
 4 import java.util.concurrent.locks.ReentrantLock;
 5 
 6 class PrintThread implements Runnable{
 7 
 8     private ReentrantLock lock=new ReentrantLock();
 9     Condition condition = lock.newCondition();
10     private int state=0;
11     
12     @Override
13     public void run() {
14         String threadName=Thread.currentThread().getName();
15         lock.lock();
16         try {
17             for(int i=0;i<9;i++){
18                 if(threadName.equals("A")){
19                     while(state%3!=0){
20                         condition.await();
21                     }
22                 }else if(threadName.equals("B")){
23                     while(state%3!=1){
24                         condition.await();
25                     }
26                 }else if(threadName.equals("C")){
27                     while(state%3!=2){
28                         condition.await();
29                     }
30                 }
31                 state++;
32                 System.out.println(threadName);
33                 condition.signalAll();
34             }
35         } catch (Exception e) {
36             // TODO: handle exception
37         }finally{
38             lock.unlock();
39         }
40         
41         
42     }
43 
44 }
45 
46 public class PrintABC{
47     public static void main(String[] args) {
48         PrintThread pt=new PrintThread();
49         Thread t1=new Thread(pt,"A");
50         Thread t2=new Thread(pt,"B");
51         Thread t3=new Thread(pt,"C");
52         t1.start();
53         t2.start();
54         t3.start();
55     }
56 }

 一条线程连续打印ABC:

class PrintABC implements Runnable{

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        lock.lock();
        int state = 0;
        try{
            while(state < 10){
                if(state % 3 == 0){
                    System.out.print("A ");
                }else if(state % 3 == 1){
                    System.out.print("B ");
                }else if(state % 3 == 2){
                    System.out.print("C ");
                }
                state++;
            }
            
        }finally {
            lock.unlock();
        }
    }
    
}
public class ThreadDemo {

    public static void main(String[] args) {
        PrintABC p = new PrintABC();
        Thread t = new Thread(p);
        t.start();
    }
}

 

转载于:https://www.cnblogs.com/noaman/p/6159253.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值