Last active
June 25, 2022 03:08
-
-
Save fzdwx/934b8e6eeb31836cc32a10b6c8087d09 to your computer and use it in GitHub Desktop.
Sequential printing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.locks.LockSupport; | |
public class test { | |
public static void main(String[] args) { | |
final Thread t6 = new Thread(new T(6, null)); | |
final Thread t5 = new Thread(new T(5, t6)); | |
final Thread t4 = new Thread(new T(4, t5)); | |
final Thread t3 = new Thread(new T(3, t4)); | |
final Thread t2 = new Thread(new T(2, t3)); | |
final Thread t1 = new Thread(new T(1, t2)); | |
t1.start(); | |
t2.start(); | |
t3.start(); | |
t4.start(); | |
t5.start(); | |
t6.start(); | |
} | |
@RequiredArgsConstructor | |
public static class T implements Runnable { | |
private final int i; | |
private final Thread next; | |
public void print() { | |
System.out.println(i); | |
if (next != null) { | |
LockSupport.unpark(next); | |
} | |
} | |
public T park() { | |
LockSupport.park(); | |
return this; | |
} | |
public void run() { | |
if (this.i == 1) { | |
this.print(); | |
} else { | |
park(); | |
this.print(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment