🔒 Closed Multithreading - wait() and notify() methods

Status
Not open for further replies.

xvein

Leecher
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();
}
}

}
 
Status
Not open for further replies.

About this Thread

  • 0
    Replies
  • 1K
    Views
  • 1
    Participants
Last reply from:
xvein

Online now

Members online
1,048
Guests online
1,088
Total visitors
2,136

Forum statistics

Threads
2,275,661
Posts
28,964,654
Members
1,231,897
Latest member
buriko2026
Back
Top