Tag: 线程线程安全

为什么这个同步方法没有按预期工作?

有人可以解释两个我为什么这些代码不输出相同的结果(两个代码之间的唯一区别在于run()方法)? 注意:第一个代码似乎没有做任何锁定! 第一个代码: class LetterThread extends Thread { private StringBuffer letter; public static void main(String[] args) { StringBuffer sbltr = new StringBuffer(“A”); LetterThread one = new LetterThread(sbltr); LetterThread two = new LetterThread(sbltr); LetterThread three = new LetterThread(sbltr); one.setName(“Thread ONE”); two.setName(“Thread TWO”); three.setName(“Thread THREE”); one.start(); two.start(); three.start(); } LetterThread(StringBuffer letter) { this.letter = letter; } public […]

Java同步

这是什么: synchronized (this) { // …some code… } 好吗? (你能写一个例子吗?)

测试最终字段的初始化安全性

我试图简单地测试JLS保证的最终字段的初始化安全性。 这是我写的一篇论文。 但是,根据我当前的代码,我无法让它“失败”。 有人可以告诉我我做错了什么,或者这只是我必须反复运行然后看到一个不幸的时机失败? 这是我的代码: public class TestClass { final int x; int y; static TestClass f; public TestClass() { x = 3; y = 4; } static void writer() { TestClass.f = new TestClass(); } static void reader() { if (TestClass.f != null) { int i = TestClass.fx; // guaranteed to see 3 int […]