1 java创建线程的几种方式
1.1 实现Runnable接口。
public class RunnableDemo implements Runnable{
public static void main(String[] args) {
//写法1
new Thread(new RunnableDemo(), "runnable线程1").start();
//写法2
new Thread(new Runnable() {
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getName());
}
}, "runnable线程2").start();
}
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getName());
}
}
1.2 继承Thread类,重写run方法。
public class ThreadDemo extends Thread{
public ThreadDemo(String name){
super.setName(name);
}
public static void main(String[] args) {
//写法1:
new ThreadDemo("thread线程1").start();
//写法二:
new Thread("thread线程2"){
@Override
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getName());
}
}.start();
}
@Override
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getName());
}
}
其实Thread类,也是实现了Runnable接口,重写了run方法,默认的run方法的逻辑:
public void run() {
if (target != null) {
target.run();
}
}
也就是,如果有target,就调用target的run,如果没有target,就什么也不做(当然,如果重新了thread的run,就会调用子类的run)。这个target是第一种创建线程方式(实现Runnable接口)传入的Runnable。
1.3 Callable/Future
带返回值
1.4 ThreadPool
实际中不会手动new Thread,因为手动创建的线程不可控,而是使用线程池
2 线程状态变更
2.1 状态变更图
2.2 查看线程状态
可以通过 jstack 命令查看线程的状态,如,有如下程序:
public class ThreadStatusDemo implements Runnable{
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "线程1").start();
new Thread(new Runnable() {
public void run() {
synchronized (this){
try {
wait(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "线程2").start();
new Thread(new Runnable() {
public void run() {
synchronized (this){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "线程3").start();
new Thread(new Runnable() {
public void run() {
while (true){
System.out.println(123344);
}
}
}, "线程4").start();
ThreadStatusDemo demo = new ThreadStatusDemo();
new Thread(demo, "线程5").start();
new Thread(demo, "线程6").start();
}
public void run() {
synchronized (this){
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
启动程序后,首先通过jps查看java进程端口号:
D:\projects\thread>jps
11424 Launcher
1332
10120 KotlinCompileDaemon
10172 Jps
10572 ThreadStatusDemo
再通过jstack查看如下:
D:\projects\thread>jstack 10572
2019-12-01 14:35:52
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.201-b09 mixed mode):
"DestroyJavaVM" #20 prio=5 os_prio=0 tid=0x0000000002cae800 nid=0x38a4 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"线程6" #19 prio=5 os_prio=0 tid=0x000000001ecc8800 nid=0x2650 waiting on condition [0x000000002018f000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at com.bxp.ThreadStatusDemo.run(ThreadStatusDemo.java:57)
- locked <0x00000006c1c06178> (a com.bxp.ThreadStatusDemo)
at java.lang.Thread.run(Thread.java:748)
"线程5" #18 prio=5 os_prio=0 tid=0x000000001ecc8000 nid=0x3478 waiting for monitor entry [0x000000002008e000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.bxp.ThreadStatusDemo.run(ThreadStatusDemo.java:57)
- waiting to lock <0x00000006c1c06178> (a com.bxp.ThreadStatusDemo)
at java.lang.Thread.run(Thread.java:748)
"线程4" #17 prio=5 os_prio=0 tid=0x000000001ecc5000 nid=0x3ed4 runnable [0x000000001ff8e000]
java.lang.Thread.State: RUNNABLE
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:326)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
- locked <0x00000006c1c0c090> (a java.io.BufferedOutputStream)
at java.io.PrintStream.write(PrintStream.java:482)
- locked <0x00000006c1c0c070> (a java.io.PrintStream)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
- locked <0x00000006c1c0c030> (a java.io.OutputStreamWriter)
at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
at java.io.PrintStream.newLine(PrintStream.java:546)
- eliminated <0x00000006c1c0c070> (a java.io.PrintStream)
at java.io.PrintStream.println(PrintStream.java:737)
- locked <0x00000006c1c0c070> (a java.io.PrintStream)
at com.bxp.ThreadStatusDemo$4.run(ThreadStatusDemo.java:42)
at java.lang.Thread.run(Thread.java:748)
"线??3" #16 prio=5 os_prio=0 tid=0x000000001ecbf800 nid=0x1630 in Object.wait() [0x000000001fe8f000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000006c1c06188> (a com.bxp.ThreadStatusDemo$3)
at java.lang.Object.wait(Object.java:502)
at com.bxp.ThreadStatusDemo$3.run(ThreadStatusDemo.java:31)
- locked <0x00000006c1c06188> (a com.bxp.ThreadStatusDemo$3)
at java.lang.Thread.run(Thread.java:748)
"线程2" #15 prio=5 os_prio=0 tid=0x000000001ecbe800 nid=0x1ee8 in Object.wait() [0x000000001fd8f000]
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000006c1c0a000> (a com.bxp.ThreadStatusDemo$2)
at com.bxp.ThreadStatusDemo$2.run(ThreadStatusDemo.java:19)
- locked <0x00000006c1c0a000> (a com.bxp.ThreadStatusDemo$2)
at java.lang.Thread.run(Thread.java:748)
"线程1" #14 prio=5 os_prio=0 tid=0x000000001ecbd800 nid=0x250c waiting on condition [0x000000001fc8f000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at com.bxp.ThreadStatusDemo$1.run(ThreadStatusDemo.java:8)
at java.lang.Thread.run(Thread.java:748)
3 线程启动,为什么调用的是start方法。
如果调用run方法,run方式只是一个普通的实例方法。我们并不是想简单的执行run,而是希望能够启动一个线程,并且让这个新启动的线程去调用run。
start方法,作用就是创建一个线程,并且线程回调run方法。
可以跟一下Thread的start方法源码,发现start中调用了start0,而start0是一个本地方法:
private native void start0();
我们可以下载hotspot源码,查看start0的具体实现。可以通过Thread.c去找到java线程相关的本地方法和hotspot源码的对应方法,如下:
从上图中可以看到,start0对应的hotspot中的方法为JVM_StartThread。JVM_StartThread方法在jvm.cpp文件中。
可以看到,JVM_StartThread中通过如下代码创建了一个JavaThread
native_thread = new JavaThread(&thread_entry, sz);
而new JavaThread实现在thread.cpp中,如下:
os::create_thread(this, thr_type, stack_sz);
可以看出,是通过调用当前操作系统的方法,创建了一个线程,所以最终的创建线程,实际是通过操作系统来实现的。
创建好线程后,最后通过调用Thread::start启动线程
Thread::start(native_thread);
Thread::start在thread.cpp中的具体实现如下:
void Thread::start(Thread* thread) {
trace("start", thread);
// Start is different from resume in that its safety is guaranteed by context or
// being called from a Java method synchronized on the Thread object.
if (!DisableStartThread) {
if (thread->is_Java_thread()) {
// Initialize the thread state to RUNNABLE before starting this thread.
// Can not set it after the thread started because we do not know the
// exact thread state at that time. It could be in MONITOR_WAIT or
// in SLEEPING or some other state.
java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
java_lang_Thread::RUNNABLE);
}
os::start_thread(thread);
}
}
可以看出,是通过操作系统启动了线程。并且在启动前,设置了线程的状态为RUNNABLE。
4 为什么线程的stop等方法不建议使用?线程的终止方式?
stop方法,只需要持有线程的对象,就可以调用。也就是可以在任意线程中去终止一个线程,这就相当于在linux下通过kill -9 强制终止一个线程类似,对于线程来说是不安全的,因为对于当前线程来说,被终止是不可知的。以及suspend(挂起),resume(恢复)等方法不建议使用也是同样的。
4.1 通过自定义标志位的方式终止线程
public class ThreadInterruptDemo {
public static boolean isInterrupt = false;
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
int i = 0;
while (!isInterrupt){
System.out.println("i = " + i ++);
}
}
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isInterrupt = true;
}
}
如上,通过控制isInterrupt 的值,可以达到终止线程的效果。
4.2 通过thread自带的interrupt()的方式终止:
public class ThreadInterruptDemo2 {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!Thread.currentThread().isInterrupted()) {
System.out.println("i = " + i++);
}
}
});
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
这种方式,可以看到,其实思想和我们第一种方式自定义标志位是类似的,只是这里标志位是线程定义,中断方法也是线程自己提供的interrupt。 thread.interrupt(),就是把Thread.currentThread().isInterrupted()设置成true。可以看一下thread.interrupt()的实现,发现调用的是本地方法:
private native void interrupt0();
根据映射,发现实际调用的是hotspot中的JVM_Interrupt
继续跟源码,发现调用的是操作系统的interrupt:
void Thread::interrupt(Thread* thread) {
trace("interrupt", thread);
debug_only(check_for_dangling_thread_pointer(thread);)
os::interrupt(thread);
}
以linux为例,找一下源码:
如上可以看到,最终就是设置interrupted的值为true。
set_interrupted方法定义:
volatile jint _interrupted; // Thread.isInterrupted state
void set_interrupted(bool z) { _interrupted = z ? 1 : 0; }
对于isInterrupted,同样的方式,最终在hotspot中的实现:
interrupted()实现为:
volatile bool interrupted() const { return _interrupted != 0; }
4.3 InterruptedException中断
上面的两种方式,都是在程序不断的判断标志位的时候,通过控制标志位来中断线程,但是如果现在在执行过程中出现了wait,sleep,join的时候,我们该如何中断线程呢?
这种情况下,也可以通过thread.interrupt();进行中断,只是执行后并不会立即中断线程的执行,而是抛出一个中断异常InterruptedException,收到这个中断异常后,我们就可以在catch中自行处理了,此时是否中断还是由当前线程说了算。
如下程序,执行后,会发现程序会继续执行,并不会真正被中断:
public class ThreadInterruptDemo4 {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!Thread.currentThread().isInterrupted()){
synchronized (this){
try {
System.out.println("i = " + i);
wait();
} catch (InterruptedException e) {
System.out.println("接收到中断异常");
e.printStackTrace();
}
}
i++;
}
}
});
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
上面程序抛出中断异常信号,但是不会被真正中断,只会抛出中断异常信号,最终是否中断,还是取决于线程本身,如果想中断,可以再收到中断异常后做相应的中断处理。
5 线程的复位重置
5.1 通过Thread.interrupetd方法对线程进行复位
public class ThreadInterruptDemo3 {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
while (true){
if (Thread.currentThread().isInterrupted()){
System.out.println("复位前:" + Thread.currentThread().isInterrupted());
Thread.interrupted();//复位
System.out.println("复位后:" + Thread.currentThread().isInterrupted());
}
}
}
});
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
从执行上面的代码中,输出true,false。中断后,Thread.currentThread().isInterrupted()变为true,通过Thread.interrupted()复位后,Thread.currentThread().isInterrupted()重新变为false。
5.2 通过InterruptException复位
在线程的中断方式中说过,处于阻塞状态的线程,通过interrupt中断,中断后并不能立即终止线程,只是会抛出中断异常,之所以没有立即中断,就是因为在中断后,又进行了复位操作。
可以看一下源码:
上图中,在sleep中,当同时满足两个条件的时候,抛出异常。
首先是Thread::is_interrupted (THREAD, true) == true,Thread::is_interrupted实现如下:
bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
assert(Thread::current() == thread || Threads_lock->owned_by_self(),
"possibility of dangling Thread pointer");
OSThread* osthread = thread->osthread();
bool interrupted = osthread->interrupted();
if (interrupted && clear_interrupted) {
osthread->set_interrupted(false);
// consider thread->_SleepEvent->reset() ... optional optimization
}
return interrupted;
}
首先获得 osthread->interrupted(),因为调用了interrupt触发了中断,所以此时osthread->interrupted()为true,然后判断如果interrupted == true并且clear_interrupted(这个应该是是否重置线程的标志,传入的为true)为true,然后重置了线程的状态,变为了false。最后返回true。
第二就是HAS_PENDING_EXCEPTION,字面意思是:是否有挂起的异常,这个变量在源码中没有找到在哪儿赋值的,暂且认为和理解中断无关,认为是false吧。
这样,那就是如果发现线程被中断了,就会把线程状态复位并且会抛出异常。
6 为什么所有的阻塞方法都会抛出InterruptException异常
因为对于阻塞方法来说,如sleep, wait,join等,阻塞后,想要让线程继续执行,都有相对应的机制或者达到一定的条件,如sleep为时间,wait和join为notify或者notifyAll。而如果在阻塞中未达到条件的情况下,通过thread.interrupt进行中断,对于线程本身来说是不正常的情况,所以这种情况下不会中断线程,但是又不能什么都不做,所以这个时候就会抛出中断异常,线程本身收到中断异常信号后,是否中断由线程自身控制。
7 如果线程wait了,就会释放CPU占用,只有notify或者notifyAll的时候才会重新抢占CPU,但是调用interrupt的时候,线程会重新执行,所以interrupt中断的时候,是否是唤醒了线程(线程处于sleep状态下同样)。
7.1 wait
先看一下interrupt的源码如下:
如上图,首先是设置线程中断状态为true,然后通过unpark接触了当前线程的阻塞状态。
7.2 sleep
sleep不是阻塞,也没有释放cpu的占用权,那sleep是怎么做的呢,这就需要看一下sleep的实现:
如上图,sleep原理大致就是一个死循环,然后对时间进行减减,当时间 <= 0的时候,就填出循环。当然,如果线程中断状态为true的时候,也会跳出循环,根据前面讲的,当跳出循环后,发现当前线程被中断了,就会复位线程状态并且抛出中断异常。