【问题标题】:Two counters on different threads counting until one is done不同线程上的两个计数器计数直到一个完成
【发布时间】:2020-05-23 17:00:13
【问题描述】:

制作 2 个线程计数器 - 从开始值计数到结束值。每次计数都应显示计数器的值。一个线程被设置为比另一个线程更小的值。当其中一个线程计数到设定值时,另一个线程停止并完成其执行。 这是我的任务,所以我用 AtomicBoolean run = new AtomicBoolean(true);

/**
 * Implements {@link Runnable} and his method {@link Runnable#run} to run until stop is set to true
 * and count is less than maxCount.
 */
public class Counter implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(Counter.class);
    private static final String MAX_COUNT_EXCEPTION_MESSAGE = "maxCount should be bigger than zero!";
    private static final int NUMBER_TO_CHECK_MAX_COUNT_VALIDATION = 1;
    private AtomicBoolean run;
    private int count;
    private int maxCount;

    /**
     * Constructs a counter with zero count and run equal to true with a specified maxCount.
     *
     * @param maxCount of the counter
     * @throws IllegalArgumentException if maxCount is smaller than 1
     */
    Counter(int maxCount, AtomicBoolean run) {
        if (maxCount < NUMBER_TO_CHECK_MAX_COUNT_VALIDATION) {
            throw new IllegalArgumentException(MAX_COUNT_EXCEPTION_MESSAGE);
        }
        this.maxCount = maxCount;
        this.run = run;
    }

    /**
     * Entry point.
     * <p>
     * Runs until run is set to false and count is less than maxCount.
     * <p>
     * On every loop {@link Counter} increment count with 1 and print the count.
     */
    @Override
    public void run() {
        while (count < maxCount && run.get()) {
            incrementCount();
            logger.info(this + " : " + count);
        }
        run.set(false);
    }

    /**
     * Used for obtaining current value for the count.
     *
     * @return count.
     */
    int getCount() {
        return count;
    }

    /**
     * Increment the count.
     */
    private void incrementCount() {
        count++;
    }
}

/**
 * Runs two counters and print the counting for both of them until one reach his maxCount then both are stopped.
 */
public class RunnerTwoCounters {
    private static final Logger logger = LoggerFactory.getLogger(RunnerTwoCounters.class);

    public static void main(String[] args) throws InterruptedException {
        AtomicBoolean run = new AtomicBoolean(true);
        Counter counter1 = new Counter(2, run);
        Thread thread1 = new Thread(counter1);
        Counter counter2 = new Counter(10, run);
        Thread thread2 = new Thread(counter2);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        logger.info(counter1 + " " + counter1.getCount());
        logger.info(counter2 + " " + counter2.getCount());
    }
}

我怎样才能使同样的事情工作但没有 Atomicboolean 只是为了使用对象锁和一些同步?

【问题讨论】:

    标签: java multithreading locking counter counting


    【解决方案1】:

    这与您最近的评论所说的一样。两个线程开始计数。当一个人到达设定点时,他们都会停下来。

    public class ThreadCounting {
    
        int value1;
        int value2;
        volatile boolean flag = true;
        public static void main(String[] args) {
            new ThreadCounting().start();
        }
    
        public void start() {
            int setPoint = 100;
            Thread begin = new Thread(() -> {
    
                while(flag && ((value1 = counter1()) <= setPoint)) {
                    System.out.println(Thread.currentThread().getName() + "     counter1 = " + value1);         
                }
                flag = false;
            });
    
            Thread finish = new Thread(() -> {
    
                while(flag && ((value2 = counter2()) <= setPoint)) {
                    System.out.println(Thread.currentThread().getName() +" counter2 = " + value2);
                }
                flag = false;
    
            });
    
            begin.start();
            finish.start();
    
        }
        int val1 = 1;
        public int counter1() {
            return val1++;
        }
        int val2 = 1;
        public int counter2() {
            return val2++;
        }
    }
    
    

    【讨论】:

    • 当我在 RunnerTwoCounters 中执行 main 方法时,控制台的输出是:
    • [Thread-0] 信息 com.sirma.javacourse.threads.twocounters.Counter - com.sirma.javacourse.threads.twocounters.Counter@66bec7ce : 1 [Thread-0] 信息 com.sirma .javacourse.threads.twocounters.Counter - com.sirma.javacourse.threads.twocounters.Counter@66bec7ce:2 [主要] 信息 com.sirma.javacourse.threads.twocounters.RunnerTwoCounters - com.sirma.javacourse.threads.twocounters。 Counter@66bec7ce 2 [main] 信息 com.sirma.javacourse.threads.twocounters.RunnerTwoCounters - com.sirma.javacourse.threads.twocounters.Counter@22d8cfe0 0
    • 两个计数器开始在两个不同的线程上计数,当一个达到设定点时,它们都停止计数
    • 查看上面的代码以了解 main 方法发生了什么,上面的类 Counter 用于创建两个实例并启动两个线程计数,直到一个计数器达到最大计数例如,如果 new Counter(5, Atomicboolean) 这个计数器将计数 0 1 2 3 4 5
    猜你喜欢
    • 1970-01-01
    • 2021-07-30
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多