+ 3

can we use two threads so that thread 1 prints a and thread 2 prints 2 alternately? output should be like this thread 1 a thread 2 b thread 1 a thread 2 b can we use wait() for this purpose?

20th Jul 2016, 4:58 PM
sreeraj g
sreeraj g - avatar
6 ответов
+ 3
It is producer consumer problem where consumer threads are waiting for the objects in Queue and producer threads put object in queue and notify the waiting threads. In your case, Write while true loop. For producer check if there is NO message in Queue, print "a", put a message in Queue and call notify()/notifyAll(). For consumer checks if there is a message in Queue, print "b", then get/remove the message from Queue and call wait(). Queue is share between producer and consumer. We also need to lock Queue object using synchronize block to avoid dead lock situation.
21st Jul 2016, 8:35 AM
WPimpong
WPimpong - avatar
+ 3
class Queue { private String msg; public void setMsg(String m){ this.msg = m; } public String getMsg(){ return this.msg; } } class Producer implements Runnable { private Queue q; public Producer (Queue q){ this.q = q; } public void run() { while (true){ try{ synchronized (q){ if (q.getMsg () == null) { q.setMsg ("a"); System .out.println ("a"); q.notify(); }else{ q.wait(); } } }catch (InterruptedException e){ } } } } class Consumer implements Runnable { private Queue q; public Consumer (Queue q){ this.q = q; } public void run() { while(true){ try{ synchronized (q){ if (q.getMsg () != null) { q.setMsg (null); System .out.println ("b"); q.notify(); }else{ q.wait(); } } }catch (InterruptedException e){ } } } } class MyClass { public static void main(String[ ] args) { Queue q = new Queue(); Thread t1 = new Thread(new Producer(q)); Thread t2 = new Thread(new Consumer(q)); t1.start(); t2.start(); } }
24th Jul 2016, 1:56 AM
WPimpong
WPimpong - avatar
+ 1
i think the easiest way to do that is to use Thread.yield() method for threads which should wait and synch all with boolean array. Whole array is "false" at the begining, after running threads, you change 1st element to "true" so 1st thread could run, you print what you want, change next element of array to "true" and present element to "false". I did sth like that in C++ and it works fine. Cheers ;)
20th Jul 2016, 9:13 PM
Lukasz Oswald
+ 1
can u try to code it?
21st Jul 2016, 12:40 AM
sreeraj g
sreeraj g - avatar
0
i didnt get it
23rd Jul 2016, 11:32 AM
sreeraj g
sreeraj g - avatar
0
you use the sleep(int milliseconds); method have one start, print, thread1.sleep(1000); have thread2.sleep(500); then print, and repeat. You don't really need to use this for something as simple as printing though.
14th Dec 2016, 6:37 AM
Jacob Waters
Jacob Waters - avatar