我跑以下代码:同步方法,而使用的等待()
class Counter extends Thread {
static int i=0;
//method where the thread execution will start
public void run(){
//logic to execute in a thread
while (true) {
increment();
}
}
public synchronized void increment() {
try {
System.out.println(this.getName() + " " + i++);
wait(1000);
notify();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//let’s see how to start the threads
public static void main(String[] args){
Counter c1 = new Counter();
Counter c2 = new Counter();
c1.setName("Thread1");
c2.setName("Thread2");
c1.start();
c2.start();
}
}
是此代码的结果(添加的行编号):
1: Thread1 0
2: Thread2 1
3: Thread2 2
4: Thread1 3
5: Thread2 4
6: Thread1 4
7: Thread1 5
8: Thread2 6
stopping...
由于增量方法是同步的并且由于其包含等待(1000)我没有预料到: 1.线程2打印2个连续打印:行2,3 我预计线程交错他们的打印 2.在第5,6行我仍然是4.
任何人都可以给我一个解释吗?
代码或者你需要是常见的两种'Thread'情况下,在同一对象上同步。为此静态方法看起来像一个黑客。 – Gray
@Gray - 是的,添加了更新 –