一、多线程实现输出循环ABC

  1、循环输出123,通过Lock锁和共享变量state实现3个线程循环执行

private static volatile int state; 
    final static Lock lock = new ReentrantLock(); 
 
    public static void main(String[] args) { 
        for (int i = 0; i < 3; i ++) { 
 
        } 
        Worker a = new Worker(3, 0); 
        Worker b = new Worker(3, 1); 
        Worker c = new Worker(3, 2); 
        a.start(); 
        b.start(); 
        c.start(); 
    } 
 
    private static class Worker extends Thread { 
 
        int mod; 
        int v; 
 
        Worker(int mod, int v) { 
            this.mod = mod; 
            this.v = v; 
        } 
 
        @Override 
        public void run() { 
            while (true) { 
                lock.lock(); 
                if (state % mod == v) { 
                    System.out.print(v + 1); 
                    state++; 
                } 
                lock.unlock(); 
            } 
        } 
    }

二、按照顺序输出1-75

    2、通过condition条件的通知机制和原子变量Inc自增实现输出1-75

    

private static final AtomicInteger inc = new AtomicInteger(); 
 
    private static Lock lock = new ReentrantLock(); 
 
 
 
    public static void main(String[] args) { 
 
        Condition conditionA = lock.newCondition(); 
 
        Condition conditionB = lock.newCondition(); 
 
        Condition conditionC = lock.newCondition(); 
 
        Worker workerA = new Worker(conditionA, conditionB, "A"); 
        Worker workerB = new Worker(conditionB, conditionC, "B"); 
        Worker workerC = new Worker(conditionC, conditionA, "C"); 
 
        workerA.start(); 
        workerB.start(); 
        workerC.start(); 
 
    } 
 
 
 
    private static class Worker extends Thread { 
        private Condition condition; 
 
        private Condition nextCondition; 
 
        private String name; 
 
        Worker(Condition condition, Condition nextCondition, String name) { 
            this.condition = condition; 
            this.nextCondition = nextCondition; 
            this.name = name; 
        } 
 
        @Override 
        public void run() { 
            lock.lock(); 
            for (int i = 0; i < 5; i++) { 
                for (int j = 0; j < 5; j ++) { 
                    System.out.println("name: " + name + " v: " + inc.incrementAndGet()); 
                } 
                nextCondition.signalAll(); 
 
                if (i < 5) { 
                    try { 
                        condition.await(); 
                    } catch (InterruptedException e) { 
                        e.printStackTrace(); 
                    } 
                } 
            } 
            lock.unlock(); 
        } 
    }

 

发布评论

分享到:

IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

insert into 配合 select批量插入详解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。