您在 Java 中遇到的最常见的并发问题是什么? [英] What is the most frequent concurrency issue you've encountered in Java?

查看:12
本文介绍了您在 Java 中遇到的最常见的并发问题是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于 Java 中常见并发问题的各种调查.一个例子可能是典型的死锁或竞争条件,或者可能是 Swing 中的 EDT 线程错误.我对可能出现的问题的广度以及哪些问题最常见感兴趣.因此,请为每条评论留下一个 Java 并发错误的具体答案,如果您看到遇到的问题,请投票.

This is a poll of sorts about common concurrency problems in Java. An example might be the classic deadlock or race condition or perhaps EDT threading bugs in Swing. I'm interested both in a breadth of possible issues but also in what issues are most common. So, please leave one specific answer of a Java concurrency bug per comment and vote up if you see one you've encountered.

推荐答案

我见过的最常见的并发问题,就是没有意识到一个线程写的字段不保证可见通过不同的线程.一个常见的应用:

The most common concurrency problem I've seen, is not realizing that a field written by one thread is not guaranteed to be seen by a different thread. A common application of this:

class MyThread extends Thread {
  private boolean stop = false;

  public void run() {
    while(!stop) {
      doSomeWork();
    }
  }

  public void setStop() {
    this.stop = true;
  }
}

只要 stop 不是 volatilesetStoprun 不是 同步 这不能保证工作.这个错误特别严重,因为 99.999% 在实践中并不重要,因为读者线程最终会看到变化 - 但我们不知道他多久看到它.

As long as stop is not volatile or setStop and run are not synchronized this is not guaranteed to work. This mistake is especially devilish as in 99.999% it won't matter in practice as the reader thread will eventually see the change - but we don't know how soon he saw it.

这篇关于您在 Java 中遇到的最常见的并发问题是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆