概述
java定义的多线程主要有如下几种状态:创建、运行、阻塞、等待、限时等待、结束
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW,
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
RUNNABLE,
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;
}
创建结束
不谈了
阻塞和等待
阻塞是竞争锁而没抢到的状态,等待是不抢了,等通知再抢的状态。
如注释所言:
阻塞是等待锁,拿到锁就进同步代码块。
等待是等待其他线程做特定的动作来唤醒:比如说object.wait()由object.notify()/object.notifyAll()唤醒、join由其他线程结束来唤醒
阻塞会竞争锁
等待不会竞争锁
限时等待
等待可能出现死锁的情况,比如所有线程都调用了object.wait(),但是没有线程进入notifyAll(),这些线程就会一直wait,所以加了个限时等待
限时等待的触发大多数是等待的接口加一个限时参数。
有一个不同的是sleep,也是限时等待。
查看线程状态
调用cmd里的jps查看所有java进程,调用jstack [pid]查看某个进程的线程状态
案例
我定义了四个线程,两个Supplier不断传输数据,一个Consumer消耗数据,但是他如果发现数据量不足100W就wait,等量到了再一次性处理。Sleep专门sleep()。Supplier和Consumer都是用相同的对象锁,他们处理同一个List
如下图可以看到,Supplier两个一个是Runnable,一个是blocker,因为他俩都在竞争锁。Consumer因为数据没达到100W他处于wait状态(没有限时)。sleep处于sleep状态
如果这里Consumer达到条件被唤醒了,他是会变成BLOCKED状态的
这是启动四个线程的代码
public class Main {
public static void main(String[] args) {
new Thread(new ConsumerRunner(),"Consumer").start();
new Thread(new SupplyRunner(), "Suppler").start();
new Thread(()-> {
try {
Thread.sleep(100000000);
} catch (InterruptedException e) {}
},"sleep").start();
new Thread(new SupplyRunner(),"suppler2").start();
}
}