What's new

Closed Multithreading - wait() and notify() methods

Status
Not open for further replies.

xvein

Addict
Joined
Mar 14, 2016
Posts
11
Reaction
2
Points
66
Mga boss, patulong po sana.
Bale, meron po kasi akong Program, yung isang class ang magse-serve as Thread ko. Sa isang class naman, gagawa ako ng maraming threads (base sa user input kung ilan).
Gusto po kasing mangyare, may unang gawain (Task1) yung mga threads na gagawin ng paunahan. Tapos may pangalawa silang gagawin (Task2) pero, dapat magantay muna na matapos lahat sa Task1 at sabay sabay ulit na gawin ang task2.
Tingin ko po kasi kelangan ko gumamit ng wait() at notify() na method. Kaso po di gumagana.
May code ako sa baba, sobrang basic lang, kung pano ko lang in-emplement yung methods.
Pano po ba gumagana yung dalawang methods? Pag nag-notify() po ba mare-resume yung isa sa mga waiting? At ganun din sa notifyAll()?
Gusto ko po kasi, mag-resume lahat ng threads (lahat sila currently waiting) at magproceed sa next Task. Maraming salamt po sa tutulong! :)

import javax.swing.*;
import java.util.*;
import java.io.*;

public class ForTest {
public static void main(String[] args) {
Thread t = new Thread(new Mythread("Juan"));
Thread t2 = new Thread(new Mythread("Pedro"));
t.start();
t2.start();
/*try{
t.join();
t2.join();
} catch (Exception e){}*/
}

}

class Mythread implements Runnable {
private String name;

Mythread(String name){
this.name = name;
}

public void run() {
synchronized (this) {
for (int a = 1; a <= 3; a++){
try {
Thread.sleep(1000);
}
catch (Exception e) {
}
//Task1 here
System.out.println(name + "'s Thread");
}
System.out.println(name + "waits...");
callNotify();
try{
wait();
}
catch (Exception e) {
}
//Task2 here
System.out.println(name + "done");
}
}

public void callNotify() {

synchronized (this) {
System.out.println("Before notify");
notify();
}
}

}
 
Last edited:
Status
Not open for further replies.

Similar threads

Back
Top