java线程join方法会释放锁吗,虽然join底层使用wait,wait是释放锁的
wait()和join()的调用方的区别:
object.wait()和thread.join()
join()的底层确实是wait(),wait()也确实释放锁,但是释放的是thread的对象锁
也就可以这么说
synchronized(obj){
thread.join(); //join不释放锁
}
synchronized(thread){
thread.join(); //join释放锁
}
下面是具体的例子:
public class JoinTest {
public static void main(String[] args) {
Object oo = new Object();
MThread thread1 = new MThread("thread1 -- ", oo);
thread1.start();
// synchronized (thread1)
synchronized (oo) {
for (int i = 0; i < 100; i++) {
if (i == 20) {
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " -- " + i);
}
}
}
}
class MThread extends Thread {
private String name;
private Object oo;
public MThread(String name, Object oo) {
this.name = name;
this.oo = oo;
}
@Override
public void run() {
synchronized (oo) {
for (int i = 0; i < 100; i++) {
System.out.println(name + i);
}
}
}
}
注意:上面代码是在i==20时加锁
当给对象oo加锁时,不释放锁(释放的是线程对象的锁而不是对象oo的锁),到20就卡住了
当给线程Thread1加锁时,释放锁