3个线程按顺序打印备用值 [英] 3 threads to print alternate values in sequence

查看:83
本文介绍了3个线程按顺序打印备用值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个实现,其中多个线程打印序列的备用值.因此,这里的thread1将打印1、4、7线程2将打印2、5、8线程3将打印3、6、9.我正在使用原子整数和模函数.

I am trying to create an implementation where multiple threads print alternate values of sequence. So here thread1 will print 1,4,7 thread2 will print 2,5,8 thread3 will print 3,6,9. I am using Atomic integer and modulo function.

以下实现在以下情况下工作良好:第一个线程打印1,4,7,第二个线程打印2,5,8,第三个线程打印3,6,9,但问题是无法保持顺序,即输出可以像1一样3,2,4,5,7,8,6,9而我希望序列保持正确的线程将打印那些值. 一种情况是我不想使用同步. [仅出于学习目的]

Below implementation works fine in the sense that first thread prints 1,4,7 while second prints 2,5,8 and third prints 3,6,9 but problem is that sequence is not maintained i.e output can be like 1,3,2,4,5,7,8,6,9 while i want sequence to be maintained as proper threads shld print those values. One condition is i don't want to use synchronize. [Just for learning purpose]

import java.util.concurrent.atomic.AtomicInteger;

public class ThreeThreadsOrderedLockLess {

    AtomicInteger sharedOutput = new AtomicInteger(0);

    public static void main(String args[]) {



        ThreeThreadsOrderedLockLess t = new ThreeThreadsOrderedLockLess();



        ThreadTasks t1 = t.new ThreadTasks(0);
        ThreadTasks t2 = t.new ThreadTasks(1);
        ThreadTasks t3 = t.new ThreadTasks(2);

        Thread ts1 = new Thread(t1);
        Thread ts2 = new Thread(t2);
        Thread ts3 = new Thread(t3);
        ts1.start();
        ts2.start();
        ts3.start();

    }

    private class ThreadTasks implements Runnable {

        private final int threadPosition;


        public ThreadTasks(int threadPosition) {
            super();

            this.threadPosition = threadPosition;
        }

        @Override
        public void run() {

            while (sharedOutput.get() < 9) {

                if (sharedOutput.get() % 3 == this.threadPosition) {

                    System.out.println("Printing output for Thread: "
                            + this.threadPosition + "  "
                            + sharedOutput.incrementAndGet());
                }
            }

        }
    }

}

推荐答案

您应该先打印,然后再增加:

You should print first, and increment after:

int value = sharedOutput.get() + 1;
System.out.println("Printing output for Thread: "
                        + this.threadPosition + "  "
                        + value);
sharedOutput.incrementAndGet();

也就是说,所有线程都在忙循环,这将导致100%的CPU使用率.您应该改为同步线程.

That said, all the threads are busy looping, which will lead to 100% CPU usage. You should synchronize the threads instead.

这篇关于3个线程按顺序打印备用值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆