【问题标题】:How can I print something after all the threads have finished?所有线程都完成后如何打印?
【发布时间】:2017-02-07 20:40:03
【问题描述】:

我正在尝试在两个线程完成运行后打印一些东西。我一直在阅读类似问题的答案,所有这些都是关于尝试 join() 方法。这对我来说是个问题,因为我尽量不破坏两个线程交替运行的方式。如果我为第一个线程编写使用该方法,第二个线程将没有机会参与我希望他们执行的操作。反之亦然。

如何在两个线程交替运行后立即打印一些内容?

我将在此处附上代码。文件 f1 和 f2 分别在不同的行中包含十个随机数。

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class JavaTip3Thread extends Thread
{
    public Thread thread;
    static int a[] = new int[10];
    static int b[] = new int[10];
    static int c[] = new int[10];
    static int index = 0;
    static boolean fin = false;
    static int ok;

    public JavaTip3Thread()
    {
        thread = new Thread(this);
    }

    public static int[] read(FileReader in)
    {
        Scanner s = new Scanner(in);
        int[] x = new int[10];;

        while(s.hasNextLine())
        {
            for(int i = 0; i < 10; i++)
            {
                x[i] = s.nextInt();
            }
        }

        s.close();
        return x;
    }

    public void sum()
    {
        while(fin != true)
        {
            int sum = 0;
            sum += a[index] + b[index];
            c[index] = sum;

            System.out.println(a[index] + " + " + b[index] + " = " + c[index]);
            index++;

            if(index == a.length)
            {
                fin = true;
            }
        }
    }

    public void run()
    {
        sum();
    } 

    public static void main(String args[]) throws IOException
    {
        FileReader in = new FileReader("D:\\IESC\\Java\\JavaTip3Thread\\src\\f1.txt");
        FileReader in2 = new FileReader("D:\\IESC\\Java\\JavaTip3Thread\\src\\f2.txt");

        a = read(in);
        b = read(in2);

        JavaTip3Thread t1 = new JavaTip3Thread();
        JavaTip3Thread t2 = new JavaTip3Thread();

        t1.start();
        t2.start();

        for(int i = 0; i < 10; i++)
        {
            System.out.println("c[" + i + "]= " + c[i] + "  ");
        }

        in.close();
        in2.close();
    }
}

【问题讨论】:

  • 为什么你认为在一个线程上调用join 会阻止另一个线程继续并发运行?\
  • 我误解了 join() 的工作方式。我认为一旦你在一个线程上调用 join() 它将停止任何其他线程直到它完成。

标签: java multithreading


【解决方案1】:
t1.start();
t2.start();

t1.join();
t2.join();

这将触发两个线程,然后才会等待第一个线程完成,然后等待第二个线程。

HTH。

【讨论】:

  • 成功了,非常感谢。线程对我来说是新事物,我往往会犯这样的错误。
猜你喜欢
  • 1970-01-01
  • 2015-10-04
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 2016-05-16
相关资源
最近更新 更多