Problema: -Esperar hasta que las roscas niño completado: Java Descripción
Paso 1: Tome FILE_NAME de entrada de usuario en hilo principal.
Paso 2: Realice 10 operaciones en ese archivo (es decir, cueres de recuento, recuentos, etc.), y todas esas 10 operaciones deben estar en hilos septados. Significa que debe haber 10 hilos secundarios.
Paso 3: El hilo principal espera hasta que se completen todos los subprocesos secundarios.
Paso 4: Resultado de la impresión.
Lo que hice: -
Hice un código de ejemplo con 3 hilos. No deseo el código de operación de archivos de su lado.
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: -
Mi código anterior no está dando respuesta correcta. ¿Cómo puedo hacer eso?
soluciones alternativas:
clase CountDownLatch hace lo mismo. Pero no quiero usar esa clase.
Miré this similar solution y quiero usar métodos de subproceso solamente.
lea sobre .join() método de Thread. – shift66
Si es tarea debe tirarla como basura la próxima vez. – Voo