简体   繁体   中英

How can I print something after all the threads have finished?

I am trying to print something after two threads have finished running. I have been reading answers to similar questions and all of them were about trying join() method. This is a problem for me as I try not to ruin the way the two threads are alternatively running. If I write use the method for the first thread, the second one won't get a chance to participate in the action I want them to do. And the other way around.

How can I print something right after both threads have finished running alternatively?

I will attach the code here. Files f1 and f2 each contain ten random numbers on separate lines.

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();
    }
}
t1.start();
t2.start();

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

This will trigger both threads and only then will wait for the first thread to finish and then wait for the second thread.

HTH.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM