Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

java - How can I get my threaded program to print specific output

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...