美文网首页
两(多)个线程交替执行最优解

两(多)个线程交替执行最优解

作者: 不知不怪 | 来源:发表于2023-01-23 14:56 被阅读0次
    import java.util.concurrent.locks.ReentrantLock;
    public class LockDemo {
        static ReentrantLock lock = new ReentrantLock(true); // 定义公平锁,用来是线程1和线程2交替执行
        public static void run(int count) {
            for (int i = 0; i < count; i++) {
                lock.lock(); // 获取锁
                try {
                    System.out.println(Thread.currentThread().getName() + "第" + i + "次执行");
                } finally {
                    lock.unlock(); // 释放锁
                }
            }
        }
        public static void main(String[] args) {
            for (int i = 0; i < 10; i++)
                new Thread(() -> run(10), "线程" + i + "-->").start();
        }
    }
    
    package com.gzz.config;
    
    import java.util.Random;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.ReentrantLock;
    
    import lombok.extern.slf4j.Slf4j;
    
    @Slf4j
    public class LockDemo {
        static ReentrantLock lock = new ReentrantLock(true); // 定义公平锁,用来是线程1和线程2交替执行
        static Random random = new Random();
    
        static void run(int count) {
            for (int i = 0; i < count; i++)
                try {
                    lock.lock();
                    int second = random.nextInt(50);
                    TimeUnit.MILLISECONDS.sleep(second);// 不论执行时间是多少,执行机会是一样的
                    log.info("{}:第{}次执行,用了{}毫秒!", Thread.currentThread().getName(), i, second);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
        }
    
        public static void main(String[] args) {
            for (int i = 0; i < 5; i++)
                new Thread(() -> run(10), "线程" + i).start();
        }
    }
    

    相关文章

      网友评论

          本文标题:两(多)个线程交替执行最优解

          本文链接:https://www.haomeiwen.com/subject/huilhdtx.html