我如何获得线程程序以打印特定输出 [英] How can I get my threaded program to print specific output
问题描述
我在处理同步Java线程,应用等待和通知时遇到问题.
I am having problem dealing with synchronization java threads, applying wait and notify..
我想弄清楚如何在一个可以交替打印答案的程序中实现这些功能.例如,person1将同时计数1-5和person2,输出应如下所示.
I want to figure out how could I implement these in a program where I can print out the answer alternately.. for example person1 will count numbers 1-5 as well as person2, the output should be like this.
person1 count 1
person2 count 1
person1 count 2
person2 count 2
person1 count 3
person2 count 3
person1 count 4
person2 count 4
person1 count 5
person2 count 5
谢谢大家.
推荐答案
您可以通过两种方式轻松地做到这一点:
You could do this easily in two ways:
-
使用两个信号量在线程之间传递打印令牌":线程1打印,向信号量A发出信号,等待信号量B然后循环.线程2等待信号量A,进行打印,向信号量B发出信号并循环.
Pass a 'print token' between the threads using two semaphores: thread 1 prints, signals semaphore A, waits on semaphore B then loops. Thread 2 waits on semaphore A, prints, signals semaphore B and loops.
编写嵌入式单线程代码.
Write in-line, single-threaded code.
这篇关于我如何获得线程程序以打印特定输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!