Strange problem with simple multithreading program in Java?

Your synchronized block in FunnyStringGenerator.next() is working fine. It will return and - alternately.

Your synchronized block in FunnyStringGenerator.next() is working fine. It will return '+' and '-' alternately. However you have a race condition in ThreadToGenerateStr.run(): System.out.

Print(gen.next()); This is equivalent to: char c = gen.next(); // Synchronized System.out. Print(c); // Not synchronized The problem occurs when: Thread 1 calls gen.next(), getting a result of '-' Thread 2 calls gen.next(), getting a result of '+' Thread 2 calls System.out.print(), writing '+' Thread 1 calls System.out.print(), writing '-' The result is that the '+' and '-' are written in the opposite order. There are various possible workarounds, e.g. : Call both gen.next() and System.out.print() in a single synchronized block (as in dogbane's answer) Make gen.next() write the character to the stream instead of returning it Make gen.next() append the character to a shared BlockingQueue and have a dedicated I/O thread taking characters from this queue and printing them.

Instead of synchronizing the method, do this: synchronized (gen) { System.out. Print(gen.next()); } You need to wrap the entire print statement in a synchronized block so that another thread cannot change the value of c before you print it. Think of it as two statements: char n = gen.next(); System.out.

Print(n).

Please use two threads for printing each character and use this concept of wait and notify.

Care to tell why down vote. – Suresh Sankar Jan 16 '11 at 17:12.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions