3 线程按顺序打印数字

编程入门 行业动态 更新时间:2024-10-27 13:32:37
本文介绍了3 线程按顺序打印数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写一个简单的代码来按顺序打印数字.场景就像

I am trying to write a simple code to print numbers in sequence. Scenario is like

Thread Number T1 1 T2 2 T3 3 T1 4 T2 5 T3 6 T1 7 T2 8 T3 9 ...and so on.

这里是

public class ThreadNumberPrinter { Object monitor = new Object(); AtomicInteger number = new AtomicInteger(1); public static void main(String[] args) { ThreadNumberPrinter tnp = new ThreadNumberPrinter(); Thread t1 = new Thread(tnp.new Printer(1, 3)); Thread t2 = new Thread(tnp.new Printer(2, 3)); Thread t3 = new Thread(tnp.new Printer(3, 3)); t3.start(); t1.start(); t2.start(); } class Printer implements Runnable { int threadId; int numOfThreads; public Printer(int id, int nubOfThreads) { threadId = id; this.numOfThreads = nubOfThreads; } public void run() { print(); } private void print() { try { while (true) { Thread.sleep(1000l); synchronized (monitor) { if (number.get() % numOfThreads != threadId) { monitor.wait(); } else { System.out.println("ThreadId [" + threadId + "] printing -->" + number.getAndIncrement()); monitor.notifyAll(); } } } } catch (InterruptedException e) { e.printStackTrace(); } } } }

但是在第二个线程运行并打印数字 2 之后,所有线程都进入等待阶段并且没有打印任何内容.我不确定我哪里做错了.任何帮助将不胜感激.

But just after 2nd thread runs and prints the number 2, all thread get into wait stage and nothing gets printed. I am not sure where I am doing wrong. Any help would be greatly appreciated.

推荐答案

嗯,问题是模 3 % 3 是 0.将您的 threadIds 更改为 0..2 而不是 1..3 并希望它应该可以工作.

Well, the problem is that modulo 3 % 3 is 0. Change your threadIds to 0..2 instead of 1..3 and hopefully it should work.

更多推荐

3 线程按顺序打印数字

本文发布于:2023-08-07 06:59:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1317625.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   顺序   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!