Ela*_*lad 5 java multithreading synchronized wait
我运行了以下代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
此代码的结果是(添加行号):
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...
Run Code Online (Sandbox Code Playgroud)
由于增量方法是同步的,因为它包含wait(1000)我没想到:1.Thread2打印2个连续打印:第2,3行我希望线程交错打印2.在第5,6行我仍然是4.
谁能给我一个解释呢?
像这样的同步实例方法:
public synchronized void foo() {
...
}
Run Code Online (Sandbox Code Playgroud)
大致相当于:
public void foo() {
synchronized(this) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
你看到这个问题吗?同步在当前实例上完成.
由于您要创建两个单独的对象,因此Thread每个increment方法将在不同的对象上同步,从而使锁无效.
您应该使增量方法保持静态(因此锁定在类本身上完成)或使用静态锁定对象:
private static final Object locker = new Object();
public void foo() {
synchronized(locker) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
最后一条建议:在java中创建线程的首选方法是实现Runnable,而不是扩展Thread.
您仅在实例级别进行同步。要在所有Counter实例之间同步,您需要该increment方法static以及synchronized.
就目前情况而言,所有线程都可以自由运行,彼此并发,因为它们不共享同步机制。
| 归档时间: |
|
| 查看次数: |
4814 次 |
| 最近记录: |