Cod*_*lue 4 java multithreading
考虑以下代码 -
class MyThread extends Thread {
private int x = 5;
public void run() {
synchronized (this) // <-- what does it mean?
{
for (int i = 0; i < x; i++) {
System.out.println(i);
}
notify();
}
}
}
class Test {
public static void main(String[] args) {
MyThread m = new MyThread();
m.start();
synchronized (m) {
try {
m.wait();
} catch (InterruptedException e) {
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,Thread m是否获得了自身的锁定?
当前线程获取MyThread类的关联实例上的锁.
在synchronized(this)被锁定的相同的对象synchronized(m)在main().
最后,
public void run() {
synchronized (this) {
Run Code Online (Sandbox Code Playgroud)
完全等同于
public synchronized void run() {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
276 次 |
| 最近记录: |