如何在java中的两个线程之间共享变量?

问题描述:

我有一个循环,这样做:如何在java中的两个线程之间共享变量?

  WorkTask wt = new WorkTask(); 
      wt.count = count; 
      Thread a = new Thread(wt); 
      a.start(); 

当workTask运行时,计数将与wt ++, 但WorkTask似乎并不改变计数,而线程之间,变量可以”在两个线程内共享,我写错了什么?谢谢。

没有看到WorkThread的代码很难确定问题,但很可能是因为缺少两个线程之间的同步。

无论何时启动线程,都无法保证原始线程或新创建的线程是先运行还是如何计划。 JVM /操作系统可以选择运行原始线程到完成,然后开始运行新创建的线程,运行新创建的线程完成,然后切换回原始线程或其他任何中间的任何线程。

为了控制线程的运行方式,您必须明确地同步它们。有几种方法可以控制线程之间的交互 ​​- 当然在单个答案中描述太多了。我会推荐使用Java教程的the concurrency trail进行广泛的概述,但在具体情况下,启动的同步机制可能是Thread.join和synchronized关键字(在the Java tutorials中描述了此关键字的一个特定用途)。

使得计数为静态变量(它看起来像每个线程都有自己的变量版本现在),并使用一个互斥体,使其线程安全的(即使用同步指令)

如果您希望从一个线程得到一个结果,我会建议你使用Callable 接口和一个ExecutorSercive来提交它。例如:

Future future = Executors.newCachedThreadPool().submit 
    (new Callable<Interger>() 
    { 
     int count = 1000; 

     @Override public Integer call() throws Exception 
     { 
      //here goes the operations you want to be executed concurrently. 
      return count + 1; //Or whatever the result is. 
     } 
    } 

    //Here goes the operations you need before the other thread is done. 

    System.out.println(future.get()); //Here you will retrieve the result from 
    //the other thread. if the result is not ready yet, the main thread 
    //(current thread) will wait for it to finish. 

这样你就不必处理同步问题等 你可以在Java单证进一步看一下:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html

从你的描述我来与以下内容展示我认为你的问题。此代码,应该输出42.但它输出41

public class Test { 
static class WorkTask implements Runnable { 
    static int count; 
    @Override 
    public void run() { 
     count++; 
    } 
} 
public static void main(String... args) throws Exception { 
    WorkTask wt = new WorkTask(); 
    wt.count = 41; 
    Thread a = new Thread(wt); 
    a.start(); 
    System.out.println(wt.count); 
} 
} 

的问题是由于之前运行的线程有机会开始打印语句。

要使当前线程(即将读取变量计数的线程)等待线程完成,请在启动thre线程后添加以下内容。

a.join();