我正在测试以下代码,我想知道线程如何访问增量方法?
我在想这个,因为 thread1 和 thread2 是从不继承工作者类的匿名类创建的对象,它们如何访问 increment() 方法?它背后的理论是什么?
public class Worker {
private int count = 0;
public synchronized void increment() {
count++;
}
public void run() {
Thread thread1 = new Thread(new Runnable() {
public void run() {
for(int i = 0; i < 10000; i++) {
increment();
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
public void run() {
for(int i = 0; i < 10000; i++) {
increment();
}
}
});
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Count is: " + count);
}
}