-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathLockSupportExample.java
66 lines (56 loc) · 2.32 KB
/
LockSupportExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package org.alxkm.patterns.locks;
import java.util.concurrent.locks.LockSupport;
/**
* Demonstrates the use of LockSupport for thread synchronization.
*
* LockSupportExample Class: The main class demonstrating the use of LockSupport.
* Task Class: A nested static class implementing Runnable, which parks its thread and waits to be unparked.
* Constructor: Takes a Thread to unpark (for demonstration purposes).
* run() Method: Parks the thread using LockSupport.park() and waits to be unparked.
* main() Method:
* mainThread: The reference to the current (main) thread.
* taskThread: A new thread running an instance of Task that parks itself.
* Thread.sleep(1000): Simulates some work in the main thread before unparking the taskThread.
* LockSupport.unpark(taskThread): Unparks the taskThread, allowing it to continue execution.
*/
public class LockSupportExample {
/**
* A task that parks the current thread and waits to be unparked.
*/
private static class Task implements Runnable {
private Thread threadToUnpark;
/**
* Constructs a new Task.
*
* @param threadToUnpark The thread that will be unparked (for demonstration purposes).
*/
public Task(Thread threadToUnpark) {
this.threadToUnpark = threadToUnpark;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is about to park.");
LockSupport.park();
System.out.println(Thread.currentThread().getName() + " is unparked and continues execution.");
}
}
/**
* Main method that demonstrates parking and unparking of threads.
*
* @param args Command line arguments.
*/
public static void main(String[] args) {
Thread mainThread = Thread.currentThread();
// Create and start a new thread that will park itself
Thread taskThread = new Thread(new Task(mainThread), "TaskThread");
taskThread.start();
try {
Thread.sleep(1000); // Simulate some work in the main thread
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// Unpark the parked thread
System.out.println("Main thread is about to unpark TaskThread.");
LockSupport.unpark(taskThread);
}
}