java线程启动不工作

标签 java multithreading runnable

我有一个涉及线程的简单练习。

(a) 创建一个实现 Runnable 的名为 SumAction 的类。 该类包含 3 个实例变量——start、end 和 sum。 start 和 end 由构造函数初始化。总和设置为 0。

(b) run() 方法应该有一个 for 循环,它应该找到从开始到结束的所有值的总和。应该有一个方法 getSum() 来返回 sum 的值。

(c) 在 main 中创建这个 Runnable 类的 2 个实例,一个以 1 和 10 作为参数,另一个以 10 和 20 为参数。

(d) 将这些实例传递给 2 个线程构造函数以创建线程 t1 和 t2。

(e) 当线程完成后,调用 getSum 从两个线程中获取总和值以求出总和。

我很确定我这样做是对的,但我仍然得到 0 的总和值。

这是我的课

public class SumAction implements Runnable {

private int start, end, sum;

public SumAction(int start, int end) {
    this.start = start;
    this.end = end;
    sum = 0;
}

@Override
public void run()
{

    for (int i = start+1; i < end; i++)
    {
      sum += i;  
    }

}

public int getSum() {
    return sum;
}
}

这里是主要内容

    SumAction run1 = new SumAction(1, 10);

    SumAction run2 = new SumAction(10, 20);

    Thread t1= new Thread(run1);

    Thread t2= new Thread(run2);


    t1.start();

    t2.start();


    System.out.println("Sum 1 : " + run1.getSum());

    System.out.println("Sum 2 : " + run2.getSum());

最佳答案

您不是在等待线程完成。您的主线程可以在其他线程完成计算之前或在它们开始之前调用 getSum。更新后的值也有可能对主线程不可见,即使该线程恰好在 println 之前完成。

在线程上调用 join 以等待它们完成,在启动线程之后和 printlns 之前添加:

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

这确保主线程在尝试打印总和之前等待其他线程完成,并且还处理了可见性问题。

在许多情况下,如果有足够的预防措施(同步、使字段易变等),则线程从另一个线程写入的字段中读取是有问题的(错误、依赖于实现,或者只是令人困惑和难以推理)没有被采取。但是在这段代码中,如果您调用 join,则不需要额外的同步来确保主线程看到 getSum 的最新值,因为有一个适用的 happens-before 规则。引用自 Oracle tutorial :

When a thread terminates and causes a Thread.join in another thread to return, then all the statements executed by the terminated thread have a happens-before relationship with all the statements following the successful join. The effects of the code in the thread are now visible to the thread that performed the join.

join 方法抛出 InterruptedException,如果线程在其中断标志设置后进入休眠或等待状态,则抛出检查异常。对于您实际上并未中断任何内容的简单示例程序,您可以将其添加到 main 方法的 throws 子句中。

关于java线程启动不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43764665/

相关文章:

java - 使用 EasyMock 模拟 Hibernate 的 SessionFactory

java - 使用DelayQueue异步执行任务: postponing an already submitted task

java - 安卓 Java : "Cannot resolve" in postDelayed

java - 可运行的计数器 'local variables referenced from an inner class must be final or effectively final'

java - Tomcat 6 是否支持 Java 8

Java:尝试编译 Hadoop 程序时找不到 com.sun.tools.javac.Main

java - 在 Spring Batch 中将 jobParameters 传递给 bean

.net - 并行化具有不同边界的多个相关操作

ios - 我需要使计时器失效/释放吗?

java - 这样使用线程效率高吗?