Skip to content

Commit 1c24e0a

Browse files
TSobalazhendrikse
authored andcommitted
[BAEL-820] Difference between wait() and sleep() in Java (eugenp#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 66471cf. * Revert of evaluation task "injecting beans" This reverts commit d2ac201. * [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.
1 parent 5b5003b commit 1c24e0a

3 files changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.baeldung.concurrent.sleepwait;
2+
3+
/***
4+
* Example of waking up a waiting thread
5+
*/
6+
public class ThreadA {
7+
private static final ThreadB b = new ThreadB();
8+
9+
public static void main(String... args) throws InterruptedException {
10+
b.start();
11+
12+
synchronized (b) {
13+
while (b.sum == 0) {
14+
System.out.println("Waiting for ThreadB to complete...");
15+
b.wait();
16+
}
17+
18+
System.out.println("ThreadB has completed. Sum from that thread is: " + b.sum);
19+
}
20+
}
21+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.concurrent.sleepwait;
2+
3+
/***
4+
* Example of waking up a waiting thread
5+
*/
6+
class ThreadB extends Thread {
7+
int sum;
8+
9+
@Override
10+
public void run() {
11+
synchronized (this) {
12+
int i = 0;
13+
while (i < 100000) {
14+
sum += i;
15+
i++;
16+
}
17+
notify();
18+
}
19+
}
20+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.concurrent.sleepwait;
2+
3+
/***
4+
* Example of wait() and sleep() methods
5+
*/
6+
public class WaitSleepExample {
7+
private static final Object LOCK = new Object();
8+
9+
public static void main(String... args) throws InterruptedException {
10+
sleepWaitInSyncronizedBlocks();
11+
}
12+
13+
private static void sleepWaitInSyncronizedBlocks() throws InterruptedException {
14+
Thread.sleep(1000); // called on the thread
15+
System.out.println("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second");
16+
17+
synchronized (LOCK) {
18+
LOCK.wait(1000); // called on the object, synchronization required
19+
System.out.println("Object '" + LOCK + "' is woken after waiting for 1 second");
20+
}
21+
}
22+
23+
}

0 commit comments

Comments
 (0)