等到子线程完成:Java

2022-09-02 22:55:31

问题描述 : -

第 1 步:在主线程处获取用户输入FILE_NAME。

第 2 步:对该文件执行 10 个操作(即计数字符、计数行等),所有这 10 个操作都必须位于分隔线程中。这意味着必须有 10 个子线程。

第 3 步:主线程将一直等到所有这些子线程完成。

第 4 步:打印结果。

我做了什么:-

我做了一个包含 3 个线程的示例代码。我不想要你这边的文件操作代码。

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

问题 :-

我上面的代码没有给出正确的答案。我该怎么做?

替代解决方案:

CountDownLatch 类也执行相同的操作。但我不想使用那个类。

我看了这个类似的解决方案,我只想使用Thread的方法。


答案 1

您可以执行以下操作:

Thread t = new Thread() {
    public void run() {
        System.out.println("text");
        // other complex code
    }
 };
 t.start();
 t.join();

这样,您将等到线程完成,然后继续。您可以多个线程:join

for (Thread thread : threads) {
  thread.join();
}

答案 2

我建议先查看 Executors 框架,然后再查看 CompletionService

然后你可以写这样的东西:

ExecutorService executor = Executors.newFixedThreadPool(maxThreadsToUse);
CompletionService completion = new ExecutorCompletionService(executor);
for (each sub task) {
    completion.submit(new SomeTaskYouCreate())
}
// wait for all tasks to complete.
for (int i = 0; i < numberOfSubTasks; ++i) {
     completion.take(); // will block until the next sub task has completed.
}
executor.shutdown();