Vấn đề: -Chờ cho đến khi đề con hoàn thành: Java Mô tả
Bước 1: Hãy FILE_NAME đầu vào từ người dùng tại thread chính.
Bước 2: Thực hiện 10 thao tác trên tệp đó (ví dụ: đếm ký tự, đếm số, vv ..) và tất cả 10 thao tác đó phải nằm trong chuỗi đề tài. Nó có nghĩa là phải có 10 chủ đề con.
Bước 3: Chủ đề chính đợi cho đến khi tất cả các chuỗi con đó hoàn tất.
Bước 4: Kết quả in.
Những gì tôi đã làm: -
tôi đã làm một mẫu mã với 3 chủ đề. Tôi không muốn mã hoạt động của tệp từ phía bạn.
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());
}
}
Vấn đề: -
mã trên của tôi không đưa ra câu trả lời đúng. Làm thế nào tôi có thể làm điều đó?
giải pháp thay thế:
lớp CountDownLatch cũng làm như vậy. Nhưng tôi không muốn sử dụng lớp đó.
Tôi đã xem this similar solution và tôi chỉ muốn sử dụng các phương thức Chỉ chủ đề.
đọc về phương thức .join() của Chủ đề. – shift66
Nếu đó là bài tập về nhà, bạn nên đổ rác như vậy vào lần sau. – Voo