add more sample about Thread state related code
This commit is contained in:
38
src/main/java/threaddemo/ThreadStateWithLockSupport.java
Normal file
38
src/main/java/threaddemo/ThreadStateWithLockSupport.java
Normal file
@ -0,0 +1,38 @@
|
||||
package threaddemo;
|
||||
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
public class ThreadStateWithLockSupport {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
Thread t1 = new Thread(LockSupport::park);
|
||||
t1.start();
|
||||
Thread.sleep(0);
|
||||
System.out.println(STR."1.\{t1.getState()}");
|
||||
LockSupport.unpark(t1);
|
||||
Thread.sleep(0);
|
||||
t1.join();
|
||||
System.out.println(STR."2.\{t1.getState()}");
|
||||
|
||||
Object o = new Object();
|
||||
Thread t2 = new Thread(() -> {
|
||||
synchronized (o) {
|
||||
try {
|
||||
System.out.println("waiting");
|
||||
o.wait();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
t2.start();
|
||||
Thread.sleep(10);
|
||||
synchronized (o) {
|
||||
System.out.println(STR."t2.1.\{t2.getState()}");
|
||||
o.notify();
|
||||
}
|
||||
Thread.sleep(0);
|
||||
System.out.println(STR."t2.2.\{t2.getState()}");
|
||||
}
|
||||
}
|
43
src/main/java/threaddemo/ThreadStateWithWait.java
Normal file
43
src/main/java/threaddemo/ThreadStateWithWait.java
Normal file
@ -0,0 +1,43 @@
|
||||
package threaddemo;
|
||||
|
||||
public class ThreadStateWithWait {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
Object object = new Object();
|
||||
|
||||
Thread t1 = new Thread(() -> {
|
||||
synchronized (object) {
|
||||
try {
|
||||
System.out.println("t1 will wait 100ms");
|
||||
object.wait(100L);
|
||||
System.out.println("t1 will wait");
|
||||
object.wait();
|
||||
System.out.println("t1 finished");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
t1.start();
|
||||
Thread.sleep(90L);
|
||||
|
||||
synchronized (object) {
|
||||
System.out.println(STR."1.t1's state: \{t1.getState()}");
|
||||
object.notify();
|
||||
Thread.sleep(100L);
|
||||
System.out.println(STR."2.t1's state: \{t1.getState()}");
|
||||
}
|
||||
|
||||
Thread.sleep(300L);
|
||||
System.out.println(STR."3.t1's state: \{t1.getState()}");
|
||||
|
||||
Thread.sleep(100L);
|
||||
|
||||
synchronized (object) {
|
||||
object.notify();
|
||||
}
|
||||
System.out.println(STR."4.t1's state: \{t1.getState()}");
|
||||
Thread.sleep(100L);
|
||||
System.out.println(STR."5.t1's state: \{t1.getState()}");
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user