往期回顾:
❀❀多线程(一):认识和创建一个线程❀❀
Thread类的常见方法
一.构造方法
方法 | 说明 |
---|---|
Thread() | 创建线程对象 |
Thread(Runnable target) | 使用 Runnable 对象创建线程对象 |
Thread(String name) | 创建线程对象,并命名 |
Thread(Runnable target, String name) | 使用 Runnable 对象创建线程对象,并命名 |
public class ThreadMethod{
public static void main(String[] args) {
Thread t1 = new Thread();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("创建一个线程");
}
});
Thread t3 = new Thread("我是一个线程");
Thread t4 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("创建一个线程");
}
},"我也是线程");
}
}
二.常见属性
1.ID
ID 是线程的唯一标识,不同线程不会重复,使用getId()获取
2.Name
name属性通常用于调试程序
Thread thread1 = new Thread(new MyThread(),"thread1");
Thread thread2 = new Thread(new MyThread(),"thread2");
System.out.println("thread1.getId() = " + thread1.getId());
System.out.println("thread2.getId() = " + thread2.getId());
System.out.println("thread1.getName() = " + thread1.getName());
System.out.println("thread2.getName() = " + thread2.getName());
3.状态
在Java当中把对线程的状态分得比原生操作系统更加细致,在
Thread
类内部,定义了一个枚举类型State
,定义了线程的6种状态,如下
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
NEW:
线程刚创建出来,还未执行start()
方法之前处于NEW
状态.Thread thread = new Thread(new ThreadMethod()); System.out.println("thread.getState() = " + thread.getState());
2.
RUNNABLE:
线程处于运行状态或者处在就绪队列,等待CPU资源Thread thread = new Thread(new ThreadMethod()); System.out.println("thread.getState() = " + thread.getState()); thread.start(); System.out.println("thread.getState() = " + thread.getState());
3.
TERMINATED
结束状态,表示线程已经执行完毕Thread thread = new Thread(new ThreadMethod()); System.out.println("thread.getState() = " + thread.getState()); thread.start(); System.out.println("thread.getState() = " + thread.getState()); Thread.sleep(100); System.out.println("thread.getState() = " + thread.getState());
4.
BLOCKED:
这个状态表示线程正在等待锁资源public class ThreadDemo implements Runnable { private static final Object lock = new Object(); public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new ThreadDemo()); thread.start(); Thread thread1 = new Thread(new ThreadDemo()); thread1.start(); Thread.sleep(1000); System.out.println("thread1.getState() = " + thread1.getState()); } @Override public void run() { synchronized (lock){ System.out.println(Thread.currentThread().getName()+" synchronized 加锁"); // 休眠 5 秒 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" synchronized 释放锁"); } } }
可以看到,当
thread
开始执行时,进入synchronized
代码块,而后来的线程thread
因为无法进入synchronized
而阻塞,进入BLOCKED
状态
5.
WAITING:
查看源码–>
发现,当线程调用上面3个方法时,会进入WAITING
状态
如:
public class ThreadState implements Runnable{ @Override public synchronized void run() { while (true) { try { this.wait(); this.notify(); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new ThreadState()); thread.start(); Thread.sleep(1000); System.out.println("thread.getState() = " + thread.getState()); } }
6.
TIMED_WAITING:
查看源码–>
当线程进入有限等待时进入TIMED_WAITING
状态.
如:
public class ThreadState implements Runnable{ @Override public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new ThreadState()); thread.start(); Thread.sleep(1000); System.out.println("thread.getState() = " + thread.getState()); } }
输出
同理join()与wait()带参数的版本可以达到同样的效果
4.优先级
优先级高的线程
理论上
来说更容易被调度到
具体的调用规则由操作系统内核决定.
thread1.setPriority(2);
System.out.println("thread1.getPriority() = " + thread1.getPriority());
**Thread提供的优先级为10个等级,1为支持得最小优先级,10为最大,如果设置的优先级不在1~10之间,会抛出异常
当创建一个线程时,默认的优先级为5
5.是否守护线程
守护线程区分与用户进程
守护进程:是一种特殊的进程,为用户进程提供服务的一种进程,当用户进程全部执行完毕后,虚拟机会kill全部的守护进程
用户进程:一个进程运行时,默认都是用户进程,要想让线程变为守护进程,需要调用setDaemon()
方法
实例 1:
当
thread
不是守护线程时,main()线程结束后,程序继续运行,且在死循环中无法退出.
class MyThread implements Runnable{
@Override
public void run() {
for (int i = 1 ; ; ++i){
System.out.println("i = " + i);
}
}
}
public class ThreadMethod{
public static void main(String[] args) {
System.out.println("main() 线程开始运行..");
Thread thread = new Thread(new MyThread());
thread.start();
}
}
当把
thread
设置为守护线程时,main()
线程结束后,程序就结束了,thread
线程被kill
System.out.println("main() 线程开始运行..");
Thread thread = new Thread(new MyThread());
// 设置thread为守护线程
thread.setDaemon(true);
thread.start();
实例 2:
形如垃圾回收线程,当用户进程结束时,也就不会产生垃圾,也就不需要垃圾回收了.
6.是否存活
run 方法执行结束前,线程存活
class MyThread implements Runnable{
@Override
public void run() {
for (int i = 1 ; i < 5; ++i){
System.out.println("i = " + i);
}
}
}
public class ThreadMethod{
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new MyThread());
System.out.println("thread.isAlive() = " + thread.isAlive());
thread.start();
System.out.println("thread.isAlive() = " + thread.isAlive());
Thread.sleep(100L); // 让线程休眠 100 ms
System.out.println("thread.isAlive() = " + thread.isAlive());
}
}
7.是否被中断
使用
thread.isInterrupted()
判断线程是否被中断,被中断返回true
使用thread.intrerupt()
中断thread
线程
三.常见方法
1.start()
重写
run()
方法时,就是指定线程任务,当我们new Thread()
时,并不代表线程开始运行,只有当我们调用start()
方法时,才会在操作系统底层创建出一个线程.
2.interrupt(),isInterrupted(),interrupted()
方法 | 说明 |
---|---|
public void interrupt() | 中断对象关联的线程,如果线程正在阻塞,则以异常方式通知,否则设置标志位为true |
public static boolean interrupted() | 判断当前线程的中断标志位是否为true ,调用后将标志位设置为false |
public boolean isInterrupted() | 判断对象关联的线程的标志位是否为true ,调用后不改变标志位 |
(1).使用自定义的变量来作为标志位.
public class ThreadMethod implements Runnable{
@Override
public void run() {
// 当isQuit为false进入循环
while (!isQuit){
System.out.println("线程运行中");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程结束");
}
private static boolean isQuit = false;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new ThreadMethod());
thread.start();
Thread.sleep(6000);
// 休眠6s后,将标志位设置位ture,循环条件不满足,结束thread线程
isQuit = true;
}
}
运行结果
(2).使用thread.isInterrupted()
代替标志位
public class ThreadMethod implements Runnable{
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()){
System.out.println("线程运行中");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程结束");
}
// private static boolean isQuit = false;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new ThreadMethod());
thread.start();
System.out.println("thread.isInterrupted() = " + thread.isInterrupted());
Thread.sleep(6000);
thread.interrupt();
System.out.println("thread.isInterrupted() = " + thread.isInterrupted());
}
}
Thread.currentThread()
为获取当前线程引用
运行上述代码,得到如下结果
可以发现,程序抛出异常,并且循环并没有结束,因为当程序执行thread.interrupt();
的时候,有两种情况1: 当线程处在运行状态,
interrupt()
会修改标志位为true
.
2.当线程处于阻塞状态时,会抛出InterruptedException()
异常,此时程序是否继续运行,取决于代码中catch
中的实现.
(3).观察interrupted()
与isInterrupted()
的区别
interrupted()
与isInterrupted()
的区别在于执行后是否将标志位重置为false
// isInterrupted()演示
public class ThreadMethod implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread.currentThread().isInterrupted() = " + Thread.currentThread().isInterrupted());
}
}
// private static boolean isQuit = false;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new ThreadMethod());
thread.start();
thread.interrupt();
}
}
输出
因为标记为未被重置,所以全部输出true
// Thread.interrupted()演示
public class ThreadMethod implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread.interrupted() = " + Thread.interrupted());
}
}
// private static boolean isQuit = false;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new ThreadMethod());
thread.start();
thread.interrupt();
}
}
输出
因为输出true
之后,标记为被重置,所以后续输出false
3.join()
当一个线程A调用某一个线程B的
join()
方法时,当前线程A将会进入等待状态,只有当B线程执行完毕之后,A线程才能继续执行.
public class ThreadMethod implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始运行");
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
System.out.println(Thread.currentThread().getName()+"结束运行");
}
// private static boolean isQuit = false;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new ThreadMethod(),"thread");
thread.start();
System.out.println("main() 线程结束...");
}
}
运行结果
可以发现,当程序运行时,main
线程先执行完毕,thread
线程才开始执行,那么,如何让thread
线程执行完毕之后,main
线程才结束呢
Thread thread = new Thread(new ThreadMethod(),"thread");
thread.start();
// 加入 thread.join() 这是,main将等待 thread结束之后才会继续往下执行
thread.join();
System.out.println("main() 线程结束...");
结果
除此之外,join()还可以传入一个毫秒数,代表最多等待多久
4.获取当前线程引用
Thread.currentThread();
5.线程休眠
public static void sleep(long millis) throws InterruptedException
,millis为休眠的毫秒数,这个方法可能会抛出异常
系列文章 ❀❀❀多线程(一):认识和创建一个线程❀❀❀ ❀❀❀多线程(三):synchronized解决线程不安全❀❀❀