How can I get my threaded program to print specific output

这一生的挚爱 提交于 2019-12-13 10:12:33

问题


I am having problem dealing with synchronization java threads, applying wait and notify..

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

Thanks guys.


回答1:


You could do this easily in two ways:

  1. 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.

  2. Write in-line, single-threaded code.




回答2:


Don't use wait and notify. Use syncronized blocks.

For an in-depth explaination of how the Java Monitor works, including code examples, you can go here: http://www.artima.com/insidejvm/ed2/threadsynch.html




回答3:


The whole purpose of threaded programs is asynchronous operation of the threads. That's how you get a performance boost because the different tasks can work on different CPUs/cores concurrently, without having to synchronize on each other. To force this sort of synchronized, lock step output is by definition forcing threads to do something atypical.

@Martin's answer provides alternatives to get it to work.



来源:https://stackoverflow.com/questions/12747704/how-can-i-get-my-threaded-program-to-print-specific-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!