Because the LockSupport can see the thread into the blocked state, thought for a moment there is no way to make the thread into the blocked state it? Because I can not get the memory only when the lock will enter the blocked state
found a bit trigger-threaded into the blocked The method on the
Internet says this:
(1) Thread sleep: Thread.sleep (long millis) method to make the thread go to a blocked state.
(2) Thread waiting: wait () method in Object class,
(3) Thread courtesy, Thread.yield () method
(4) Thread self-closing, join () method,
(5) The suspend () and resume () methods The
above method may make the thread blocked, but I think that only when the blocking state is entered can the thread be blocked. It may be that I am too awkward. I think this statement is a bit biased. , Because I remember the following picture in my mind:
but is it possible that the book is wrong?
Then try it
1.sleep () method
public static void main(String[] args) {
new Thread(()->{
try {
System.out.println("正在睡眠");
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t1").start();
}
Use jps to view the thread
Use jstack to view the status of the thread:
Oh, TimeWaiting, the thread is in a timeout waiting state
2. The wait method
Object o = new Object();
Thread t2 = new Thread(() -> {
synchronized (o) {
try {
System.out.println("执行等待!");
o.wait();
} catch (InterruptedException e) {
}
}
}, "t2");
t2.start();
Thread.sleep(100000);
o.notify();
waitting state
3.synchronized (blocked state)
Object o = new Object();
new Thread(() -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o) {
}
}, "t1").start();
//让t2 先拿到锁,然后就一直处于wait状态,我们再来观察t1
new Thread(() -> {
synchronized (o) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t2").start();
4. join
Thread t1 = new Thread(() -> {
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1");
t1.start();
//先让t1 跑起来 观察t2
Thread.sleep(10);
Thread t2 = new Thread(() -> {
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t2");
t2.start();
5.yield
The method of giving up the CPU time slice is a bit difficult to operate, because it is too short to give up a time slice
I will think of a way to update later
6.LockSupport
Thread t1 = new Thread(() -> {
LockSupport.park();
}, "t1");
t1.start();
Thread.sleep(100000);
LockSupport.unpark(t1);
Conclusion: The
last LockSupport can overthrow all the previous ones: only entering the blocking state can be called a blocking thread
Perhaps this part is not specifically defined, so you don't need to delve into it, you just need to understand it, and you shouldn't use this part of knowledge in daily development.
And if you want to block the thread: all of the
above except yield can play the role of blocking the thread, instead of letting the thread enter the blocking thread state defined by java