当前位置:网站首页>The difference between thread join and object wait
The difference between thread join and object wait
2022-07-26 09:26:00 【new hilbert()】
Object Wait Usage of :
When a thread calls wait When , Will release the sync lock , The thread then enters a wait state . Other suspended threads will compete for this lock , Continue to execute after getting the lock .
Thread join Usage of :
Another thread is invoked in a thread running. JOIN Method , The current thread stops executing , Wait until the new join The incoming thread has finished executing , Will continue to carry out !!
Join Principle analysis :
Thread It's the object :thread It's also object lock , It can be owned and released by other threads
synchronized: By synchronized Keyword locked , Enter this method , This indicates that the thread has obtained the object lock at this time
wait: When a thread calls an object wait When the method is used , The lock will be released , The thread then enters a wait state . The thread of the waiting queue in the object lock will compete for the lock , Continue to execute after getting the lock , It ensures that other threads get the lock first , Continue to use ,cpu When scheduling sleep(sleep It won't give up the lock )
Java Join Method resolution
public final synchronized void join(long millis) throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
public final native void wait(long timeout) throws InterruptedException;
Call directly wait Method Can replace Join Methods? ?
answer : Definitely not ,wait The method should cooperate with Synchronized Together with ,wait Is to release the object lock , The precondition of releasing the object lock is to obtain the object lock . Enter into Synchronized Code block , It means that this thread has obtained the lock .
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
System.out.println("main start");
Thread t1 = new Thread(() -> {
try {
Thread.sleep(1000);
System.out.println("test");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
// Release t1 This object lock , Give way t1 Thread to execute , because t1 Threads also need t1 Thread this object lock
t1.join();
System.out.println("main end");
}
}
The operation results are as follows :
main start
test
main end
Call directly wait() Result , No, Synchronized The blessing . Because at this time, the thread is not sure whether it has acquired the lock , An object lock error will be reported IllegalMonitorStateException
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
System.out.println("main start");
Thread t1 = new Thread(() -> {
try {
Thread.sleep(1000);
System.out.println("test");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t1.wait();
System.out.println("main end");
}
}
Running results
main start
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at lock .ThreadTest.ThreadJoin.main(ThreadJoin.java:23)
test
Multiple threads call t1.join Analysis of the situation of
Join It's just that after grabbing the lock , Let the lock out , Join the queue and wait for the lock again
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
System.out.println("main start");
Thread t1 = new Thread(() -> {
try {
Thread.sleep(1000);
System.out.println("test");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
try {
t1.join();
System.out.println(" t2 test");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
t1.join();
System.out.println("main end");
}
}
result 1
main start
test
t2 test
main end
result 2
main start
test
main end
t2 test
main Threads and t2 Threads All gave up lock resources , Only t1 The thread did not commit the act of releasing the object lock , Can guarantee t1 Threads are the first to complete , however t2 and main Threads , Who is in t1 It is uncertain that the thread obtains the object lock after
problem :Join The essence is wait ,wait Is the need to notify Awakened , So who performs notify Awakened by join What about blocked threads ?
Because the following code has no place to call notify, The only possibility is t1 The thread did the operation , Thread object lock released .
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
System.out.println("main start");
Thread t1 = new Thread(() -> {
try {
Thread.sleep(1000);
System.out.println("test");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t1.wait();
System.out.println("main end");
}
}
answer : Is the thread object lock itself , After the thread executes, it will call exit Method , exit Method Would call ensure_join
Thread.cpp
void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
assert(this == JavaThread::current(), "thread consistency check");
...
// Notify waiters on thread object. This has to be done after exit() is called
// on the thread (if the thread is the last thread in a daemon ThreadGroup the
// group should have the destroyed bit set before waiters are notified).
ensure_join(this);
assert(!this->has_pending_exception(), "ensure_join should have cleared");
...
}
ensure_join In the method , call lock.notify_all(thread); Wake up all the waiting thread Thread object lock thread , It means calling join The thread whose method is blocked will be awakened .
static void ensure_join(JavaThread* thread) {
// We do not need to grap the Threads_lock, since we are operating on ourself.
Handle threadObj(thread, thread->threadObj());
assert(threadObj.not_null(), "java thread object must exist");
ObjectLocker lock(threadObj, thread);
// Ignore pending exception (ThreadDeath), since we are exiting anyway
thread->clear_pending_exception();
// Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
// Clear the native thread instance - this makes isAlive return false and allows the join()
// to complete once we've done the notify_all below
java_lang_Thread::set_thread(threadObj(), NULL);
lock.notify_all(thread);
// Ignore pending exception (ThreadDeath), since we are exiting anyway
thread->clear_pending_exception();
}
边栏推荐
- 对象型的集合按某个属性的值进行去重
- 【Flutter -- 布局】Align、Center、Padding 使用详解
- 您的登录IP不在管理员配置的登录掩码范围内
- The provincial government held a teleconference on safety precautions against high temperature weather across the province
- Solve "note: one or more layouts are missing the layout_width or layout_height attributes."
- TabbarController的封装
- wap端微信h5支付,用于非微信浏览器
- nodejs中mysql的使用
- Original root and NTT 5000 word explanation
- Byte buffer stream & character stream explanation
猜你喜欢

Your login IP is not within the login mask configured by the administrator

Paper notes: knowledge map kgat (unfinished temporary storage)

volatile 靠的是MESI协议解决可见性问题?(下)

Windows下Redis哨兵模式搭建

PMM(Percona Monitoring and Management )安装记录

Use of off heap memory

js中树与数组的相互转化(树的子节点若为空隐藏children字段)

Li Mu D2L (V) -- multilayer perceptron

Server memory failure prediction can actually do this!

登录模块用例编写
随机推荐
服务器内存故障预测居然可以这样做!
Hbuilderx runs the wechat developer tool "fail to open ide" to solve the error
异常处理机制二
【Mysql】一条SQL语句是怎么执行的(二)
JS - DataTables control on the number of displays per page
[shutter -- layout] detailed explanation of the use of align, center and padding
小程序纪录
搜索模块用例编写
点击input时,不显示边框!
Paper notes: knowledge map kgat (unfinished temporary storage)
js中树与数组的相互转化(树的子节点若为空隐藏children字段)
Stm32+mfrc522 completes IC card number reading, password modification, data reading and writing
Windows通过命令备份数据库到本地
mysql5.7.25主从复制(单向)
"Could not build the server_names_hash, you should increase server_names_hash_bucket_size: 32"
2B和2C
Polynomial open root
Redis principle and usage - installation and distributed configuration
Personality test system V1.0
OnTap 9 file system limitations