class Test {
private int data;
int result = 0;
public void m() {
result += 2;
data += 2;
System.out.print(result + " " + data);
}
}
class ThreadExample extends Thread {
private Test mv;
public ThreadExample(Test mv) {
this.mv = mv;
}
public void run() {
synchronized(mv){
mv.m();
}
}
}
class ThreadTest {
public static void main(String args[]) {
Test mv = new Test(); // 声明并初始化对data赋默认值
Thread t1 = new ThreadExample(mv);
Thread t2 = new ThreadExample(mv);
Thread t3 = new ThreadExample(mv);
t1.start();
t2.start();
t3.start();
}
}
A. 0 22 44 6
B. 2 42 42 4
C.2 24 46 6
D. 4 44 46 6
解析:
- 使用synchronized关键字加同步锁, 使三个线程一次顺序操作m()方法
- t1.start(); 使得result = 2; data = 2
- t2.start(); 使得result = 4; data = 4;
- t3.start(): 使得result = 6; data = 6;
- System.out.print(result+” “+data); print方法, 不会自动换行, 所以输出结果是2 24 46 6