加入Threads java

时间:2017-03-26 17:01:49

标签: java multithreading join

我有这段代码:

public final class Hello() {

    static long x1;
    static long x2;

    public static long start(args...) {
       //commands...
       Thread left = new Thread(){ 
           @Override
           public void run(){ 
               x1 = amethod(args...);   
           }
       }; 
       Thread right = new Thread(){ 
           @Override
           public void run(){ 
               x2 = amethod(args...);  
           }
       }; 
       left.start(); 
       right.start();
       x = x1 + x2;
   }
   return x;
}

名为"left"的线程和名为"right"的线程是独立线程。我的问题是,如果x得到正确的值,或者在线程结束之前执行命令"x=x1+x2"

我必须强制使用join()

3 个答案:

答案 0 :(得分:1)

无法保证x1x2在您将x添加到一起时将其设置为所需的值。

保证这一点的唯一方法是在两个线程上调用join()

答案 1 :(得分:1)

  

名为" left"和名为" right"是独立的线程。我的问题是,如果x得到正确的值或命令" x = x1 + x2"将在线程结束之前执行。我必须强制使用join()?

是的,您必须致电x = x1 + x2。在主线程到达join()行之前,无法保证2个后台线程甚至启动

此外,每当您在两个线程之间共享数据时,您还需要担心线程之间的内存同步。当您使用线程加入时,您可以保证所有线程内存与调用left.start(); right.start(); // left and right threads are running in the background... // we join with them so we can make sure they have finished // and we can sync with their memory updated of x1 and x2 left.join(); right.join(); x = x1 + x2; 的线程同步。

所以在主线程中你应该这样做:

ExecutorService

最后,作为替代方案,您可以使用Future<Integer>ExecutorService threadPool = Executors.newFixedThreadPool(2); // spawn our jobs into the pool Future<Integer> future1 = threadPoll.submit(new Callable<Integer>() { ... }); Future<integer> future2 = threadPool.submit(new Callable<Integer>() { ... }); // once all jobs have been submitted you shutdown the pool threadPool.shutdown(); // the get() methods here wait for the threads to finish and return a value int x = future1.get() + future2.get(); 来执行以下操作:

ExecutorService

Future负责线程生成,call()将返回#pragma once class movement { private: Ball *b; int size; public: movement(void) { size=0; } Ball getBall(int i) { return b[i]; } void insertBall(Ball n) { Ball *temp=new Ball[size+1]; for (int i = 0;i<size; i++) { temp[i]=b[i]; } temp[size]=n; delete []b; b=temp; size++; } void update(Ball food,Ball b) { for (int i = 0; i < size; i++) { //if ((b->getPoint().getX() == b->getPoint().getY()) if (food.getPoint().getX == b.getPoint().getX() && food.getPoint().getY == b.getPoint().getY()) { insertBall(b); } } } }; 方法中的值。非常有用。

答案 2 :(得分:0)

join()函数确保当前线程将等待调用线程完成,然后才会执行下一个语句。因此,在将x1和x2的值相加之前,我们必须使用以下内容, left.join(); right.join();