How can I get my thread program to print a specific result

I had a problem synchronizing java threads using wait and notify.

I want to find out how I can implement them in a program where I can print the answer one at a time. For example, person1 will count the 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.

-6
source share
3 answers

You can do this easily in two ways:

  • Pass a “print token” between threads using two semaphores: thread 1, signals of semaphore A, wait on semaphore B, then loops. Topic 2 waits for semaphore A, prints, signals semaphore B and loops.

  • Introductory single-threaded code.

+1
source

Do not use wait and notify. Use synchronized blocks.

For a detailed explanation of how Java Monitor works, including code samples, you can go here: http://www.artima.com/insidejvm/ed2/threadsynch.html

0
source

The whole purpose of streaming programs is the asynchronous operation of threads. This is how you get performance gains, because different tasks can run on different CPUs / cores at the same time, without having to synchronize with each other. To force this type of synchronized blocking output signal, by definition, cause threads to do something atypical.

Answer

@Martin provides alternatives to make it work.

0
source

All Articles