Problema: -Attendere che le discussioni bambino completato: Java Descrizione
Fase 1: Prendere FILE_NAME input da utente a thread principale.
Passaggio 2: Eseguire 10 operazioni su quel file (cioè contare i caratteri, contare le linee ecc.) E tutte queste 10 operazioni devono essere in thread setto. Significa che ci devono essere 10 thread figli.
Passaggio 3: Il thread principale attende fino a quando tutti i thread figli sono stati completati.
Punto 4: Stampa risultato.
Quello che ho fatto: -
ho fatto un codice di esempio con 3 fili. Non voglio il codice operativo del file dalla tua parte.
public class ThreadTest {
// This is object to synchronize on.
private static final Object waitObject = ThreadTest.class;
// Your boolean.
private static boolean boolValue = false;
public final Result result = new Result();
public static void main(String[] args) {
final ThreadTest mytest = new ThreadTest();
System.out.println("main started");
new Thread(new Runnable() {
public void run() {
System.out.println("Inside thread");
//Int initialiser
new Thread(new Runnable() {
public void run() {
System.out.println("Setting integer value");
mytest.result.setIntValue(346635);
System.out.println("Integer value seted");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
//String initialiser
new Thread(new Runnable() {
public void run() {
System.out.println("Setting string value");
mytest.result.setStringValue("Hello hi");
System.out.println("String value seted");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
//Boolean initialiser
new Thread(new Runnable() {
public void run() {
System.out.println("Setting boolean value");
mytest.result.setBoolValue(true);
System.out.println("Boolean value seted");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
System.out.println("Thread is finished");
//Notify to main thread
synchronized (ThreadTest.waitObject) {
ThreadTest.boolValue = true;
ThreadTest.waitObject.notifyAll();
}
}
}).start();
try {
synchronized (ThreadTest.waitObject) {
while (!ThreadTest.boolValue) {
ThreadTest.waitObject.wait();
}
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("main finished");
System.out.println("Result is : " + mytest.result.toString());
}
}
Problema: -
Il mio codice di cui sopra non sta dando risposta corretta. Come lo posso fare?
soluzioni alternative:
classe CountDownLatch fa lo stesso. Ma non voglio usare quella classe.
Ho cercato this similar solution e voglio utilizzare solo i metodi di Thread.
letto sul metodo .join() della discussione. – shift66
Se è compito, dovresti buttarlo nel cestino la prossima volta. – Voo