常用方法
线程状态图
启动线程
.start() 启动线程:
我们要知道start()实例方法是启动该线程,此时线程由创建态变为就绪态,当线程为就绪态时就可以等待操作系统进行调度,调度到之后就执行线程的run方法(线程的任务)。
public class ThreadFirst {
public static void main(String[] args)throws InterruptedException {
//新创建一个线程
Thread newthread= new Thread(new Runnable() {
@Override
public void run()
{
try {
Thread.sleep(99999999999L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
newthread.start();
}
}
停止线程
停止线程
- 建议线程正常停止—>利用次数,不建议死循环。
- 建议使用标志位—>设置一个标志位
- 不要使用stop或者destroy等过时或者JDK不建议使用的方法
退出标识
使用退出标识,使得线程正常退出,即当run方法完成后进程终止
package com.it
//测试停止线程
public class ThreadStop implements Runnable {
//设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("Thread "+i++ +"running");
}
}
//2.设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
ThreadStop threadStop = new ThreadStop();
new Thread(threadStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main线程"+i);
if (i==900){
//调用stop方法切换标志位,让线程停止
threadStop.stop();
System.out.println("线程停止.........");
}
}
}
}
使用stop强行中断线程(不推荐使用)
使用stop强行中断线程(此方法为作废过期方法),不推荐使用,暴力终止,可能使一些清理性的工作得不到完成。还可能对锁定的内容进行解锁,容易造成数据不同步的问题。
suspend方法暂停线程(不推荐使用)
多线程中使用 thread.suspend() 方法暂停线程, suspend()方法容易发生死锁。调用suspend()的时候,目标线程会停下来,但却仍然持有在这之前获得的锁定。此时,其他任何线程都不能访问锁定的资源,除非被”挂起”的线程恢复运行。对任何线程来说,如果它们想恢复目标线程,同时又试图使用任何一个锁定的资源,就会造成死锁。所以不应该使用suspend(),而应在自己的Thread类中置入一个标志,指出线程应该活动还是挂起。若标志指出线程应该挂起,便用 wait()命其进入等待状态。若标志指出线程应当恢复,则用一个notify()重新启动线程。
使用 interrupt() 中断线程
原文连接:https://www.cnblogs.com/liyutian/p/10196044.html
现在我们知道了使用 stop() 方式停止线程是非常不安全的方式,那么我们应该使用什么方法来停止线程呢?答案就是使用 interrupt() 方法来中断线程。
需要明确的一点的是:interrupt() 方法并不像在 for 循环语句中使用 break 语句那样干脆,马上就停止循环。调用 interrupt() 方法仅仅是在当前线程中打一个停止的标记,并不是真的停止线程。
也就是说,线程中断并不会立即终止线程,而是通知目标线程,有人希望你终止。至于目标线程收到通知后会如何处理,则完全由目标线程自行决定。这一点很重要,如果中断后,线程立即无条件退出,那么我们又会遇到 stop() 方法的老问题。
事实上,如果一个线程不能被 interrupt,那么 stop 方法也不会起作用。
我们来看一个使用 interrupt() 的例子:
public class InterruptThread1 extends Thread{
public static void main(String[] args) {
try {
InterruptThread1 t = new InterruptThread1();
t.start();
Thread.sleep(200);
t.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
super.run();
for(int i = 0; i <= 200000; i++) {
System.out.println("i=" + i);
}
}
}
从输出的结果我们会发现 interrupt 方法并没有停止线程 t 中的处理逻辑,也就是说即使 t 线程被设置为了中断状态,但是这个中断并不会起作用,那么该如何停止线程呢?
这就需要使用到另外两个与线程中断有关的方法了:
public boolean Thread.isInterrupted() //判断是否被中断
public static boolean Thread.interrupted() //判断是否被中断,并清除当前中断状态
这两个方法使得当前线程能够感知到是否被中断了(通过检查标志位)。
所以如果希望线程 t 在中断后停止,就必须先判断是否被中断,并为它增加相应的中断处理代码:
@Override
public void run() {
super.run();
for(int i = 0; i <= 200000; i++) {
//判断是否被中断
if(Thread.currentThread().isInterrupted()){
//处理中断逻辑
break;
}
System.out.println("i=" + i);
}
}
输出结果,for 循环在执行完成前就提前结束了:
在上面这段代码中,我们增加了 Thread.isInterrupted() 来判断当前线程是否被中断了,如果是,则退出 for 循环,结束线程。
这种方式看起来与之前介绍的“使用标志位终止线程”非常类似,但是在遇到 sleep() 或者 wait() 这样的操作,我们只能通过中断来处理了。
public static native void sleep(long millis) throws InterruptedException
Thread.sleep() 方法会抛出一个 InterruptedException 异常,当线程被 sleep() 休眠时,如果被中断,这会就抛出这个异常。
(注意:Thread.sleep() 方法由于中断而抛出的异常,是会清除中断标记的。)
线程休眠(.sleep())
.sleep() 线程休眠:
- sleep (时间)指定当前线程阻塞的毫秒数;
- sleep存在异常 InterruptedException;
- sleep时间达到后线程进入就绪状态;
- sleep可以模拟网络延时,倒计时等。
- 每一个对象都有一个锁,sleep不会释放锁;
//模拟倒计时
public class TestSleep {
public static void main(String[] args) {
try {
tenDown() ;
} catch (InterruptedException e) {
e.printStackTrace() ;
}
}
public static void tenDown() throws InterruptedException {
int num = 10;
while (true) {
Thread.sleep(millis:1000) ;
System.out.println(num--);
if (num<=0){
break;
}
}
}
}
线程礼让(.yield())
.yield() 线程礼让:线程让步就是让该线程由运行态转变为就绪态。一般用于让其他线程完成自己的任务后,再执行当前线程的工作。
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让cpu重新调度,礼让不一定成功!看CPU心情
package com.it;
//测试线程礼让
public class ThreadYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"A线程==>").start();
new Thread(myYield,"B线程==>").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行!");
Thread.yield(); //礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行!");
}
}
开启线程礼让前:
开启线程礼让后:
Join(线程强制执行 )
.join 线程强制执行 :
- Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
- 可以想象成插队
package com.it;
//测试Join方法
public class ThreadJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("vip线程"+i);
}
}
public static void main(String[] args) throws InterruptedException {
ThreadJoin join = new ThreadJoin();
Thread thread = new Thread(join);
thread.start();
for (int i = 0; i < 10; i++) {
if (i==6){
thread.join();
}
System.out.println("main线程"+i);
}
}
}
执行结果:
设置线程优先级
- Java提供一个线程调度器来监控程序中 启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
- 线程的优先级用数字表示,范围从1~10.
- Thread.MIN PRIORITY = 1;
- Thread.MAX_ PRIORITY = 10;
- Thread.NORM_ PRIORITY = 5;
- 使用以下方式 取优先级
- getPriority() .setPriority (int xxx)
优先级低只是意味着获得调度的概率低
,并不是优先级低就不会被调用了,这都是看CPU的调度
package com.it.Test;
//测试线程的优先级
public class TestPriority {
public static void main(String[] args) {
//主线程的默认优先级为5
System.out.println(Thread.currentThread().getName()+"==>"+Thread.currentThread().getPriority());//获取线程的有优先级
MyPriority priority = new MyPriority();
Thread t1 = new Thread(priority);
Thread t2 = new Thread(priority);
Thread t3 = new Thread(priority);
Thread t4 = new Thread(priority);
Thread t5 = new Thread(priority);
//先设置优先级再启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
t5.setPriority(Thread.MIN_PRIORITY);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"==>"+Thread.currentThread().getPriority());//获取线程的有优先级
}
}
守护(daemon)线程
守护(daemon)线程:(.setDaemon(true))
- 线程分为用户线程和守护线程
- 用户线程是我们平常创建的普通线程
- 守护线程是用来服务于用户线程;不需要上层逻辑介入。
- 虚拟机必须确保用户线程执行完毕(如:main线程)
- 虚拟机不用等待守护线程执行完毕,如:后台记录操作日志,监控内存,垃圾回收等待…
package com.it;
//测试守护线程
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true); //默认是false表示是用户线程,正常的线程都是用户线程...
thread.start();
new Thread(you).start();
}
}
//守护线程
class God implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("上帝与你同在!");
}
}
}
//用户线程
class You implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("活着");
}
System.out.println("死了.........");
}
}
执行结果: