【问题标题】:Java Threads - Synchronized(this)Java 线程 - 同步(本)
【发布时间】:2012-04-26 06:16:47
【问题描述】:

请看下面的程序

public class TestVolatile implements Runnable {

    public static volatile int counter;
    public static String lock = "lock";

    public static void main(String[] args) {
        Thread t1 = new Thread(new TestVolatile(),"Thread-1");
        Thread t2 = new Thread(new TestVolatile(),"Thread-2");
        t1.start();
        t2.start();
    }

    public void run() {
        synchronized(this) {
            System.out.println(Thread.currentThread()+"-"+counter);
            counter++;
        }
    }
}

如果我多次运行这个程序,我会得到 3 个不同的结果。

首先是

线程[Thread-1,5,main]-0
线程[Thread-2,5,main]-0

秒是

线程[Thread-1,5,main]-0
线程[Thread-2,5,main]-1

第三个是

线程[Thread-1,5,main]-1
线程[Thread-2,5,main]-0

但如果将锁定对象从“this”更改为“lock”,我会得到 2 个不同的结果

首先是

线程[Thread-1,5,main]-0
线程[Thread-2,5,main]-1

秒是

线程[Thread-1,5,main]-1
线程[Thread-2,5,main]-0

我在编写程序时的假设是,在任何一种情况下,“计数器”都不应该在两个语句中都为 0。
谁能解释一下?

【问题讨论】:

标签: java multithreading synchronized


【解决方案1】:

您创建了两个 TestVolatile 对象。 “this”关键字指的是在线程中运行的 TestVolatile 对象。因此,您不会在第一个示例中对同一个对象进行同步。

如果您像这样更改代码,那么第一个示例开始工作:

public static void main(String[] args) {
    TestVolatile testVolatile = new TestVolatile();
    Thread t1 = new Thread(testVolatile,"Thread-1");
    Thread t2 = new Thread(testVolatile,"Thread-2");
    t1.start();
    t2.start();
}

【讨论】:

    【解决方案2】:

    这可能不是你要找的,但如果你想避免使用synchronizedvolatile,你应该使用AtomicInteger 的实例: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html

    使用getAndIncrement 方法显示与您的示例相同的行为。

    public class TestVolatile implements Runnable {
    
        public static AtomicInteger counter = new AtomicInteger();
        public static void main(String[] args) {
            Thread t1 = new Thread(new TestVolatile(),"Thread-1");
            Thread t2 = new Thread(new TestVolatile(),"Thread-2");
            t1.start();
            t2.start();
        }
    
        public void run() {
            System.out.println(Thread.currentThread() + " - " + counter.getAndIncrement());
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多