[BAEL-820] Difference between wait() and sleep() in Java (#1708)
* injecting beans * XML-based configuration replaced with Java Config. * [BAEL-431] Exploring TestRestTemplate. * Revert of evaluation task "XML-based configuration replaced with Java Config." This reverts commit 66471cf0574c85f8ff514ec4caf5ba44ebba1a74. * Revert of evaluation task "injecting beans" This reverts commit d2ac20185e636245bc0ae0b4ccb952965de88e28. * [BAEL-431] fix to the tests in TestRestTemplateBasicLiveTest. * [BAEL-431] added more meaningful user and password for auth. * [BAEL-820] examples of wait() and sleep() methods. * [BAEL-820] wait() and sleep() examples.
This commit is contained in:
parent
5b5003b391
commit
1c24e0a2cf
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.concurrent.sleepwait;
|
||||
|
||||
/***
|
||||
* Example of waking up a waiting thread
|
||||
*/
|
||||
public class ThreadA {
|
||||
private static final ThreadB b = new ThreadB();
|
||||
|
||||
public static void main(String... args) throws InterruptedException {
|
||||
b.start();
|
||||
|
||||
synchronized (b) {
|
||||
while (b.sum == 0) {
|
||||
System.out.println("Waiting for ThreadB to complete...");
|
||||
b.wait();
|
||||
}
|
||||
|
||||
System.out.println("ThreadB has completed. Sum from that thread is: " + b.sum);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.concurrent.sleepwait;
|
||||
|
||||
/***
|
||||
* Example of waking up a waiting thread
|
||||
*/
|
||||
class ThreadB extends Thread {
|
||||
int sum;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (this) {
|
||||
int i = 0;
|
||||
while (i < 100000) {
|
||||
sum += i;
|
||||
i++;
|
||||
}
|
||||
notify();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.concurrent.sleepwait;
|
||||
|
||||
/***
|
||||
* Example of wait() and sleep() methods
|
||||
*/
|
||||
public class WaitSleepExample {
|
||||
private static final Object LOCK = new Object();
|
||||
|
||||
public static void main(String... args) throws InterruptedException {
|
||||
sleepWaitInSyncronizedBlocks();
|
||||
}
|
||||
|
||||
private static void sleepWaitInSyncronizedBlocks() throws InterruptedException {
|
||||
Thread.sleep(1000); // called on the thread
|
||||
System.out.println("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
|
||||
|
||||
synchronized (LOCK) {
|
||||
LOCK.wait(1000); // called on the object, synchronization required
|
||||
System.out.println("Object '" + LOCK + "' is woken after waiting for 1 second");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue