我有一段看起来像这样的代码:
片段A:
class Creature {
private static long numCreated;
public Creature() {
synchronized (Creature.class) {
numCreated++;
}
}
public static long numCreated() {
return numCreated;
}
}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,由于读取numCreated不同步,如果Thread-A Creature在下午1点创建一个,并且Thread-B numCreated()在下午2点读取,则numCreated()可能返回0或1(即使Thread-A已在1.05pm完成初始化对象) ).
所以我添加synchronized到numCreated():
代码片段B:
class Creature {
private static long numCreated;
public Creature() {
synchronized (Creature.class) {
numCreated++;
}
}
public static synchronized long numCreated() { // add "synchronized"
return numCreated;
}
}
Run Code Online (Sandbox Code Playgroud)
并且一切都很好,除了我在想,如果我将它修改为Snippet C,变量是否numCreated仍然正确同步?
片段C: …
我有以下线程,每200ms只打印一个点:
public class Progress {
private static boolean threadCanRun = true;
private static Thread progressThread = new Thread(new Runnable()
{
public void run() {
while (threadCanRun) {
System.out.print('.');
System.out.flush();
try {
progressThread.sleep(200);
} catch (InterruptedException ex) {}
}
}
});
public static void stop()
{
threadCanRun = false;
progressThread.interrupt();
}
public static void start()
{
if (!progressThread.isAlive())
{
progressThread.start();
} else
{
threadCanRun = true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我用这段代码启动线程(现在):
System.out.println("Working.");
Progress.start();
try {
Thread.sleep(10000); //To be replaced with code that …Run Code Online (Sandbox Code Playgroud)