相关疑难解决方法(0)

Java volatile变量是否会在读取之前强制执行之前的关系?

我有一段看起来像这样的代码:

片段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完成初始化对象) ).

所以我添加synchronizednumCreated():

代码片段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: …

java concurrency multithreading

8
推荐指数
1
解决办法
1165
查看次数

使用System.out.print与println的多线程问题

我有以下线程,每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)

java multithreading

6
推荐指数
1
解决办法
3771
查看次数

标签 统计

java ×2

multithreading ×2

concurrency ×1