理解java中的同步 [英] understanding synchronized in java
问题描述
为什么通常线程样本在同步块中放置这么多代码.根据我的理解,在以下情况下,synchronized仅用于锁定b以便进行等待和通知:
Why usually threading samples put so many code in synchronized block. According to my understanding in following case synchronized is used just for locking b for wait and notify:
主类ThreadA:
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
synchronized(b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
System.out.println(Thread.currentThread().getName());
}
}
}
和ThreadB类:
class ThreadB extends Thread {
int total;
public void run() {
synchronized(this)
{
System.out.println();
for(int i=0;i<100;i++)
{
System.out.println(Thread.currentThread().getName());
total += i;
}
notify();
}
}
}
如果仅将wait
和notify
放在synchronized
块中,将会发生什么变化:
What will change if I put just wait
and notify
in synchronized
block:
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
try {
System.out.println("Waiting for b to complete...");
synchronized(b) { b.wait();}
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
System.out.println(Thread.currentThread().getName());
}
}
推荐答案
根据我的理解,在以下情况下,同步仅用于锁定b以进行等待和通知
According to my understanding in following case synchronized is used just for locking b for wait and notify
您的理解是错误的.
synchronized
也用于:
- 相互排斥,以确保一次只有一个线程执行特定监视器保护"的代码
- 确保跨线程的内存访问正确(一个线程可以看到另一线程所做的更改)
如果我只等待并在同步块中进行通知,将会发生什么变化
What will change if I put just wait and notify in synchronized block:
在这种特殊情况下,它会根据竞争条件而有所不同-在原始代码中,如果新的thread
开始在 之前在原始线程中到达同步块,则开始执行,直到第二个线程完成为止,它不会达到等待b完成"的作用……这时它将永远在wait
中阻塞.
In this particular case, it will make a difference based on a race condition - in the original code, if the new thread
starts executing before the synchronized block is reached in the original thread, it won't get as far as "Waiting for b to complete" until the second thread has finished... at which point it will block forever in wait
.
请注意,在Thread
监视器上等待是一个绝妙的主意,因为Thread
在内部由Thread
使用.
Note that it's a really bad idea to wait on Thread
monitors, as wait/notify
is used internally by Thread
.
简而言之,您使用的示例以各种方式开头都是不好的例子-但是同步 不仅用于wait/notify
.
In short, the example you've used is a bad one to start with in various ways - but synchronization is used for more than just wait/notify
.
这篇关于理解java中的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!