+ 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?
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.
+ 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();
}
}
+ 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 ;)
+ 1
can u try to code it?
0
i didnt get it
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.