等到子线程完成:Java

And*_*ndy 12 java multithreading

问题描述 : -

第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());
    }
}
Run Code Online (Sandbox Code Playgroud)

问题: -

我上面的代码没有给出正确的答案.我怎样才能做到这一点?

替代解决方案:

CountDownLatch类也是如此.但我不想使用那个班级.

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

Bor*_*jev 33

你可以做:

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

这样你就会等到线程完成然后继续.你可以join多个线程:

for (Thread thread : threads) {
  thread.join();
}
Run Code Online (Sandbox Code Playgroud)

  • @GünayGültekin构造for循环中的所有线程并调用它们的`start`方法.但是不要在这个循环中调用`join` - 在第一次连接之后,主线程将等待第一个线程完成,然后才开始第二个线程.在第一个for循环之后执行第二个只在所有线程上调用`join`时,可以等待它们,因为它们都已经启动了 (7认同)
  • 我试过了,但是一个线程等待另一个线程开始执行。所有线程不会同时执行。我想启动所有线程并等待所有线程完成。 (2认同)

dav*_*veb 11

我建议先查看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();
Run Code Online (Sandbox Code Playgroud)