请看下面的节目
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个不同的结果。
第一是
线程-1,5,main-0
线程-2,5,主-0
二是
线程-1,5,main-0
线程-2,5,main-1
三是
线程-1,5,main-1
线程-2,5,主-0
但是,如果将锁对象从"this“更改为" lock ",则会得到两个不同的结果
第一是
线程-1,5,main-0
线程-2,5,主-1
二是
线程-1,5,main-1
线程-2,5,主-0
在编写程序时,我的假设是,无论在哪种情况下,“计数器”都不应该在两个语句中都为0。
有人能解释一下吗?
发布于 2012-04-26 06:23:40
创建两个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();
}发布于 2012-04-26 06:35:19
这可能不是您要寻找的东西,但是如果您想避免使用synchronized和volatile,您应该使用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());
}
}https://stackoverflow.com/questions/10328154
复制相似问题