Thread2等待Thread1完成启动问题? Java

问题描述 投票:0回答:1

因此,我有一个简单的代码,我想使用Thread1将值i打印10次,在Thread2的10次之后,最后打印计数(应该为20)。我正在使用“ .join()”,但是结果是执行Thread1和Thread2的随机时间,然后总和是正确的。如何先打印所有Thread's1循环,然后再打印Tread's2?

class MyClass extends Thread {  

     public static synchronized void incount() {
         SimpleThreads.count++;
     } 
        public void run() { 

            for(int i=0; i<10; i++) { 
                    incount();  
                    System.out.println(Thread.currentThread().getId()+" value : " + i);
            }
        }           
    }

public class SimpleThreads {

     static int count=0;

    public static void main(String[] args) {

        MyClass thread1 =new MyClass();
        MyClass thread2 =new MyClass();

        thread1.start(); 
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(" Sum : "+count);
    }
}

结果:

11 value : 0
10 value : 1
11 value : 1
10 value : 2
11 value : 2
10 value : 3
11 value : 3
11 value : 4
11 value : 5
11 value : 6
11 value : 7
11 value : 8
11 value : 9
10 value : 4
10 value : 5
10 value : 6
10 value : 7
10 value : 8
10 value : 9
 Sum : 20

因此,我有一个简单的代码,我想使用Thread1将值i打印10次,在Thread2的10次之后,最后打印计数(应该为20)。我正在使用“ .join()”,但是...

java multithreading thread-sleep
1个回答
0
投票

您正在启动Thread2,然后在join()上调用thread1。这就是为什么两个线程基本上同时运行并且联接不会影响其他两个线程的run()的原因。

© www.soinside.com 2019 - 2024. All rights reserved.