线程状态和调度

 线程状态有新生状态,就绪状态,运行状态,阻塞状态,死亡状态

1. 新建(NEW):新创建了一个线程对象。

2. 可运行(RUNNABLE):线程对象创建后,其他线程(比如main线程)调用了该对象的start()方法。该状态的线程位于可运行线程池中,等待被线程调度选中,获取cpu 的使用权 。

3. 运行(RUNNING):可运行状态(runnable)的线程获得了cpu 时间片(timeslice) ,执行程序代码。
4. 阻塞(BLOCKED):阻塞状态是指线程因为某种原因放弃了cpu 使用权,也即让出了cpu timeslice,暂时停止运行。直到线程进入可运行(runnable)状态,才有机会再次获得cpu timeslice 转到运行(running)状态。阻塞的情况分三种: 

(一). 等待阻塞:运行(running)的线程执行o.wait()方法,JVM会把该线程放入等待队列(waitting queue)中。
(二). 同步阻塞:运行(running)的线程在获取对象的同步锁时,若该同步锁被别的线程占用,则JVM会把该线程放入锁池(lock pool)中。
(三). 其他阻塞:运行(running)的线程执行Thread.sleep(long ms)或t.join()方法,或者发出了I/O请求时,JVM会把该线程置为阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时,线程重新转入可运行(runnable)状态。

5. 死亡(DEAD):线程run()、main() 方法执行结束,或者因异常退出了run()方法,则该线程结束生命周期。死亡的线程不可再次复生。

 

下面对几种线程状态的实现举例说明:

* 终止线程
 * 1,线程正常执行完毕
 * 2,加入标志位

 1 package cn.ftf.thread;
 2 /**
 3  * 终止线程
 4  * 1,线程正常执行完毕
 5  * 2,加入标志位
 6  * 
 7  * @author 房廷飞
 8  *
 9  */
10 public class TerminateThread implements Runnable{
11     
12     public TerminateThread(String name) {  //给线程起个名字方便查看
13         super();
14         this.name = name;
15     }
16     //加入标志位
17     private boolean flag=true;
18     private String name;
19 
20     @Override
21     public void run() {
22         int i=0;
23         //在run()里关联标志位
24         while(flag) {
25             System.out.println(name+"-->"+i++);
26         }
27 
28     }
29     
30     //对外提供方法改变状态
31     public void stopThread() {
32         flag=false;
33     }
34     
35     
36     public static void main(String[] args) {
37         TerminateThread tt=new TerminateThread("线程");
38         Thread th=new Thread(tt);  //线程新生状态
39         th.start();  //线程就绪状态
40         
41         for(int i=0;i<100;i++) {
42             //当遍历到88时,改变标志位为flase
43             if(i==88) {
44                 tt.stopThread();  //控制了线程的终止
45                 System.out.println("tt.终止了!");
46             }
47             System.out.println("遍历--》"+i);
48         }
49     }
50 }

Thread.sleep() 线程阻塞,常用于延时

 1 package cn.ftf.thread;
 2 /**
 3  * sleep()模拟发生网络延迟,有了延迟就放大了发生问题的可能
 4  * @author 房廷飞
 5  *
 6  */
 7 
 8 
 9 public class BlockedSleep {
10     public static void main(String[] args) {
11         new Thread(new Web12306()).start();
12         new Thread(new Web12306()).start();
13         new Thread(new Web12306()).start();
14     }
15 }
16 
17 class Web12306 implements Runnable{
18     static int ticketNums=10;
19 
20     @Override
21     public void run() {
22         while(true) {
23             if(ticketNums<0) {
24                 break;
25             }
26             
27             //模拟延时
28             try {
29                 Thread.sleep(200);
30             } catch (InterruptedException e) {
31                 // TODO Auto-generated catch block
32                 e.printStackTrace();
33             }
34             System.out.println(ticketNums--);
35         }
36         
37     }
38     
39 }

.join()线程阻塞,插队线程,.join()的线程先执行完

 1 package cn.ftf.thread;
 2 /**
 3  * join插队线程,合并线程,等.join()的线程走完才能继续进行其他线程,.join需要实例化对象才能调用
 4  * @author 房廷飞
 5  *
 6  */
 7 public class BlockedJoinTest {
 8     
 9     public static void main(String[] args) throws InterruptedException {
10         Thread th=new Thread(()-> {
11             for(int i=0;i<100;i++) {
12                 System.out.println("A  "+i);
13             }
14             
15         });
16         th.start();
17         for(int i=0;i<100;i++) {
18             System.out.println("B  "+i);
19             if(i==50) {
20                 //Thread.sleep(20000);
21                 th.join();    //线程th插队,等th线程走完才能继续进行其他(main)线程
22             }
23         }
24     }
25 }

Thread.yield() 回到就绪状态

 1 package cn.ftf.thread;
 2 /**
 3  * yield礼让线程不阻塞,直接进入就绪状态,公平竞争
 4  * @author user
 5  *
 6  */
 7 public class YieldTest {
 8     public static void main(String[] args) {
 9         MyYield my=new MyYield();
10         new Thread(my,"A进程").start();
11         new Thread(my,"B进程").start();
12         new Thread(my,"C进程").start();
13     }
14 
15 }
16 
17 class MyYield implements Runnable {
18 
19     @Override
20     public void run() {
21         System.out.println(Thread.currentThread().getName()+"开始");
22         
23         Thread.yield();    //礼让一下,返回就绪状态
24         
25         System.out.println(Thread.currentThread().getName()+"结束");
26         
27     }
28     
29 }

线程状态:

 1 package cn.ftf.thread;
 2 
 3 import java.lang.Thread.State;
 4 
 5 public class AllState {
 6     public static void main(String[] args) throws InterruptedException {
 7         Thread th=new Thread(()->{
 8             for(int i=0;i<5;i++) {
 9                 try {
10                     Thread.sleep(200);
11                 } catch (InterruptedException e) {
12                     // TODO Auto-generated catch block
13                     e.printStackTrace();
14                 }
15                 System.out.println("hahahaha...");
16             }
17         }) ;
18         //观察状态
19         State state=th.getState();
20         System.out.println(state.toString());
21         th.start();
22         state=th.getState();
23         System.out.println(state.toString());
24         Thread.sleep(100);
25         state=th.getState();
26         System.out.println(state.toString());
27         Thread.sleep(1000);
28         state=th.getState();
29         System.out.println(state.toString());
30 
31     }
32 }
33 
34 /*
35 NEW
36 RUNNABLE
37 TIMED_WAITING
38 hahahaha...
39 hahahaha...
40 hahahaha...
41 hahahaha...
42 hahahaha...
43 TERMINATED
44 */

线程的优先级:

 1 package cn.ftf.thread;
 2 /**
 3  * 优先级
 4  * @author 房廷飞
 5  *
 6  */
 7 public class PriorityTest {
 8     public static void main(String[] args) {
 9         System.out.println(Thread.currentThread().getPriority());  //获得当前线程的优先级
10         
11         Thread th=new Thread(new Test01(),"零");
12         Thread th1=new Thread(new Test01(),"一");
13         Thread th2=new Thread(new Test01(),"二");
14         Thread th3=new Thread(new Test01(),"三");
15         Thread th4=new Thread(new Test01(),"四");
16         Thread th5=new Thread(new Test01(),"五");
17         
18         //在启动前设置优先级,优先级:1~10
19         th.setDaemon(true);
20         
21         th.setPriority(Thread.MAX_PRIORITY);  //获得最大优先级
22         th1.setPriority(Thread.MAX_PRIORITY);
23         th2.setPriority(10);                  //可以自己设置
24         th3.setPriority(Thread.MIN_PRIORITY);
25         th4.setPriority(Thread.MIN_PRIORITY);
26         th5.setPriority(1);
27         
28     
29         th.start();
30         th1.start();
31         th2.start();
32         th3.start();
33         th4.start();
34         th5.start();
35 
36         
37     }
38 
39 }
40 
41 class Test01 implements Runnable{
42 
43     @Override
44     public void run() {
45         System.out.println("线程。。。"+Thread.currentThread().getName());
46     }
47 }
48 /*
49  * 运行结果
50 
51 5
52 线程。。。零
53 线程。。。二
54 线程。。。一
55 线程。。。五
56 线程。。。三
57 线程。。。四
58 */
59 /*
60 设置守护线程:
61 JVM不会随守护线程的停止而停止,只关心用户线程
62 th.setDaemon(true);
63 
64 */

猜你喜欢

转载自www.cnblogs.com/fangtingfei/p/11253122.html