请教一个问题, 如果没有锁,Java线程间是如何交换数据的?如果想了解Java对这个问题的描述,我该看那个资料。
各个线程有各自的Working memory,如果没有锁,它们会错误的交换数据?
1. Java的内存模型是怎样的呢?
根据这篇文章所述(Java 线程/内存模型的缺陷和增强),Java中有一个主内存(Main Memory),Java中每个线程都有各自的内存(Working Memory)。
2 如果没有锁,程序是不对的,我们该怎样理解这个错误呢。
下面是不带锁的代码(附件为代码)
public class TestVolatile {
public static void main(String[] args) throws InterruptedException {
final ConcurrencyTest01 test = new ConcurrencyTest01();
Thread thread11 = new Thread(new BasicTestRunnable(test, 11));
Thread thread12 = new Thread(new BasicTestRunnable(test, 12));
thread11.start();
thread12.start();
}
}
public class BasicTestRunnable implements Runnable {
ConcurrencyTest01 test;
int type;
public BasicTestRunnable(ConcurrencyTest01 test, int type) {
super();
this.test = test;
this.type = type;
}
@Override
public void run() {
while (true) {
switch (type) {
case 1:
test.one();
break;
case 2:
test.two();
break;
case 11:
test.eleven();
break;
case 12:
test.twelve();
break;
}
}
}
}
public class ConcurrencyTest01 {
static int i = 0, j = 0;
int x = 0, y = 0;
static void one() {
i++; j++;
}
static void two() {
System.out.println("i=" + i + " j=" + j);
}
void eleven() {
x++; y++;
}
void twelve() {
System.out.println("x=" + x + " y=" + y);
}
}
输出结果
x=1443657134 y=1443657161
x=1443658375 y=1443658405
x=1443659636 y=1443659665
x=1443661310 y=1443661339
x=1443662965 y=1443662995
x=1443665005 y=1443665035
x=1443666585 y=1443666614
x=1443667781 y=1443667812
x=1443668924 y=1443668954
这是我的疑惑,望赐教。