zoukankan      html  css  js  c++  java
  • java-线程-ABCABC

    public class OneByOne {
    
        private Lock lock = new ReentrantLock();
        private Condition conditionA = lock.newCondition();
        private Condition conditionB = lock.newCondition();
        private Condition conditionC = lock.newCondition();
    
        private String firstChar = "A";
    
        private int count = 3;
    
        class A implements Runnable{
            public void run(){
                try{
                    lock.lock();
                    for(int i = 0 ; i < count; i++){
                        while(!Thread.currentThread().getName().equals(firstChar)){
                            conditionA.await();
                        }
                        System.out.println("A");
                        firstChar = "B";
                        conditionB.signal();
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
            }
        }
    
        class B implements Runnable{
            public void run(){
                try{
                    lock.lock();
                    for(int i = 0 ; i < count; i++){
                        while(!Thread.currentThread().getName().equals(firstChar)){
                            conditionB.await();
                        }
                        System.out.println("B");
                        firstChar = "A";
                        conditionA.signal();
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
            }
        }
        public static void main(String[] args){
            OneByOne obo = new OneByOne();
            Thread a = new Thread(obo.new A());
            Thread b = new Thread(obo.new B());
            a.setName("A");
            b.setName("B");
            a.start();
            b.start();
        }
    }
    
  • 相关阅读:
    DB2中创建表
    orcle定时备份
    db2的定时备份
    web.xml 中 resource-ref 的注意事项
    bootstrap
    jQuery
    web聊天室
    Django web 进阶
    Django自定义分页、bottle、Flask
    Queue、进程、线程、协程
  • 原文地址:https://www.cnblogs.com/xckxue/p/8745129.html
Copyright © 2011-2022 走看看