我是靠谱客的博主 欣慰月亮,这篇文章主要介绍线程状态,优先级,守护线程基础详解,现在分享给大家,希望可以做个参考。

线程状态,优先级,守护线程基础详解

    • 线程状态
      • 停止线程
      • 线程休眠
      • 线程礼让
      • 线程强制执行
      • 线程状态检测
    • 线程的优先级
    • 守护线程
    • 线程同步

线程状态

  1. 创建状态(new 之后就是创建状态
  2. 就绪状态(调用start方法之后
  3. 调用状态(cpu调度之后
  4. 阻塞状态(当调用sleep,wait,或同步锁时,线程进入阻塞状态,就是代码不往下执行。阻塞状态接触后,重新进入就绪状态,等待cpu的调度。)
  5. 死亡状态(线程中断或者结束,一旦进入死亡状态,就不能再次启动)

停止线程

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.wang.threadDemo2; /** * @author: 王海新 * @Date: 2021/2/26 17:55 * @Description: 测试 stop * 1 建议线程正常停止————》利用次数,不建议使用死循环 * 2 建议使用标志位————》设置一个标志位 * 3 不要使用stop或者destroy等过时 或者jdk不建议使用的方法 */ public class TestStop implements Runnable{ //1.设置一个标志位 private Boolean flag = true; @Override public void run() { int i = 0 ; while (flag) { System.out.println("run...." + i++); } } //2.设置一个公开的方法停止线程,转换标志位 public void stop(){ this.flag = false; } public static void main(String[] args) { TestStop testStop = new TestStop(); new Thread(testStop).start(); for (int i = 0; i < 1000; i++) { System.out.println("main"+i); if (i == 900) { //调用stop方法切换标志位,让程序停止 testStop.stop(); System.out.println("线程该停止了.."); } } } }

如果无法设置标志位让线程停止,最好就让线程自己停止。

线程休眠

  • sleep指定当前线程阻塞的毫秒数
  • 存在异常interruptedException
  • 可以模拟网络延时,倒计时等
  • 每个对象都有一个锁,sleep不会释放锁

如下代码,如果去掉延时,在cpu运行很快的时候,基本上不会出现有人拿了一样的票的问题

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.wang.threadDemo2; import com.wang.threadDemo.TestThread4; /** * @author: 王海新 * @Date: 2021/2/27 12:00 * @Description: 模拟线程延时,证明了线程是不安全的。模拟延时起到了放大问题的发生性 */ public class TestSleep implements Runnable{ private int ticketNumbel = 10; //火车票 @Override public void run() { while (true){ if (ticketNumbel <= 0) { break; } //添加延迟 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 拿到了第" + ticketNumbel-- + "张票"); } } public static void main(String[] args) { TestSleep ticket = new TestSleep(); new Thread(ticket,"小明").start(); new Thread(ticket,"老师").start(); new Thread(ticket,"黄牛党").start(); new Thread(ticket,"键盘侠").start(); } }
  • 还可以模拟倒计时,

    复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    package com.wang.threadDemo2; /** * @author: 王海新 * @Date: 2021/2/27 12:04 * @Description: 模拟倒计时 */ public class TestSleep2 { 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(1000); System.out.println(num --); if (num &lt; 0){ break; } } } }--
  • 打印当前系统时间

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.wang.threadDemo2; import java.text.SimpleDateFormat; import java.util.Date; /** * @author: 王海新 * @Date: 2021/2/27 12:04 * @Description: 打印当前系统时间 */ public class TestSleep3 { public static void main(String[] args) { //获取当前时间 Date startTime = new Date(System.currentTimeMillis()); while (true) { System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } startTime = new Date(System.currentTimeMillis()); } } }

线程礼让

礼让不一定成功,因为礼让的线程和被礼让的线程都处在就绪状态,等待cup的调度,有可能礼让的线程再次被调度。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.wang.threadDemo2; /** * @author: 王海新 * @Date: 2021/2/27 14:12 * @Description: 线程礼让。线程礼让是正在运行的线程退出到就绪状态。和其它线程一起等待cpu的调度 * 当然cpu可能还会调度到刚刚退出的线程,所以礼让不一定成功 */ public class TestYield { 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() + "线程停止了"); } }

线程强制执行

start之后是就绪状态,cup有可能会调度。所以会在main线程200之前出现穿插情况。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.wang.threadDemo2; /** * @author: 王海新 * @Date: 2021/2/27 15:36 * @Description: 线程强制执行。 * 合并线程,等到次线程结束后,再执行其它线程 */ public class TestJoin implements Runnable{ @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println("我是vip" + i); } } public static void main(String[] args) throws InterruptedException { TestJoin testJoin = new TestJoin(); Thread thread = new Thread(testJoin); thread.start(); for (int i = 0; i < 1000; i++) { if (i == 200) { thread.join(); } System.out.println("我是主线程"+ i); } } }

线程状态检测

我们可以通过线程检测。来对线程进行一些操作。比如发现线程阻塞了一两分钟中,大概就是线程崩溃了。我们就可以选择终止线程

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.wang.threadDemo2; /** * @author: 王海新 * @Date: 2021/2/27 16:49 * @Description: 观察测试线程的状态 * 线程一旦死亡结束,就不能再重新启动。 * */ public class TestState { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread( () -> { for (int i = 0; i < 5; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("/"); }); //观察初始状态 System.out.println(thread.getState()); //观察启动后 thread.start(); System.out.println(thread.getState()); //只要线程不终止,就一直输出状态(输出的为阻塞时的状态。) while (thread.getState() != Thread.State.TERMINATED) { Thread.sleep(100); System.out.println(thread.getState()); } //一旦线程结束,就不能再次调用这个线程,调用会报错 //thread.start(); } }

线程的优先级

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.wang.threadDemo; /** * @author: 王海新 * @Date: 2021/2/27 17:12 * @Description: 设置线程的优先级,设置的权重高,不一定就优先执行。只不过是cpu调度到此线程的权重高。 * 这会导致有一个线程倒置的问题。 * //如果需要设置优先级,应该先设置优先级,再启动(调用start方法) */ public class TestPriority { public static void main(String[] args) { //打印main线程的优先级 System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority()); MyPriority myPriority = new MyPriority(); Thread t1 = new Thread(myPriority,"1"); t1.start(); Thread t2 = new Thread(myPriority,"2"); t2.setPriority(3); t2.start(); Thread t3 = new Thread(myPriority,"3"); t3.setPriority(2); t3.start(); Thread t4 = new Thread(myPriority,"4"); t4.setPriority(Thread.MAX_PRIORITY);//最大权重,10 t4.start(); } } class MyPriority implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority()); } }

守护线程

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.wang.threadDemo; import sun.awt.windows.ThemeReader; /** * @author: 王海新 * @Date: 2021/2/27 17:35 * @Description: 守护线程(如:gc垃圾回收线程,后台记录操作日志) * 线程分为守护线程和用户线程 * 虚拟机不需要等待守护线程执行完毕 * 虚拟机必须确保用户线程执行完毕 */ public class TestDeamon { public static void main(String[] args) { You you = new You(); God god = new God(); Thread thread = new Thread(god);//守护线程 神 thread.setDaemon(true);//设置为守护线程。默认为false,正常的线程都是用户线程 thread.start(); new Thread(you).start();// 你 用户线程 //用户线程跑完之后,还跑了一会守护线程,是因为虚拟机关闭需要一段时间 } } class You implements Runnable{ @Override public void run() { for (int i = 0; i < 3600; i++) { System.out.println("你开心的活着" + i); } } } class God implements Runnable{ @Override public void run() { while (true) { System.out.println("上帝守护这你"); } } }

线程同步

  • 线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用

  • 并发:一个对象被多个线程同时操作

  • 队列和锁:是解决并发问题的方法,但是同时会消耗性能。

    • 由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制。synchronized
  • 每个对象都有一个锁,sleep不会释放锁。

  • 存在的问题

    • 一个线程持有锁,会导致其它需要此锁的线程挂起
    • 在多线程竞争下,加锁,释放锁,回导致较多的上下文切换和调度延时,引起性能问题。
    • 如果一个优先级高的线程等待一个优先级低的线程,会导致性能倒置的问题。
  • 三大线程不安全案例

    • 复制代码
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      package com.wang.syn; /** * @author: 王海新 * @Date: 2021/2/28 16:40 * @Description: 不安全的买票, * 线程不安全,有负数,有重复的 */ public class UnsafeBuyTicket { public static void main(String[] args) { BuyTicket buyTicket = new BuyTicket(); new Thread(buyTicket,"小明").start(); new Thread(buyTicket,"小红").start(); new Thread(buyTicket,"小芳").start(); new Thread(buyTicket,"小蓝").start(); } } class BuyTicket implements Runnable{ //票 private int ticketNums = 10; boolean flage = true;//外部停止方法 @Override public void run() { //买票 while (flage) { try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } private void buy() throws InterruptedException { //判断是否有票 if (ticketNums <= 0) { flage = false; return; } //模拟延时 Thread.sleep(1000); //买票 System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums -- +"张"); } }
    • 每个线程在自己的工作内存交互,内存控制不当,会造成数据不一致。

  • 银行取钱问题

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.wang.syn; /** * @author: 王海新 * @Date: 2021/2/28 16:59 * @Description: 不安全的取钱,两个人去银行取钱 * */ public class UnsafeBank { public static void main(String[] args) { Account account = new Account(100,"结婚基金"); Drawing you = new Drawing(account, 50, "你"); Drawing girlFriend = new Drawing(account, 100, "grilFriend"); you.start(); girlFriend.start(); } } /********************************************************************************************************************* * @Author: 王海新 * @Date: 17:05 2021/2/28 * @Version: 1.0.0 * @Description: 账户 */ class Account{ String name; int money; public Account( int money,String name) { this.name = name; this.money = money; } } /********************************************************************************************************************* * @Author: 王海新 * @Date: 17:05 2021/2/28 * @Version: 1.0.0 * @Description: 银行 模拟取款 */ class Drawing extends Thread{ //账户 Account account; //取了多少钱 int DrawingMoney; //现在手里有多少钱 int nowMoney; //构造器,将变量初始化 Drawing(Account account,int DrawingMoney,String name){ super(name); this.account = account; this.DrawingMoney = DrawingMoney; } @Override public void run() { if (account.money - DrawingMoney < 0) {//判断账户中的钱是否够取 System.out.println(this.getName() + "钱不够,取不到"); return; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //更新取钱后账户钱的剩余 account.money = account.money - DrawingMoney; //更新用户手中的钱 nowMoney = nowMoney + DrawingMoney; System.out.println(account.name + "账户中的钱为" + account.money); //Thread.currentThread()就是返回一个Thread对象,所以我们可以用this System.out.println(this.getName()+ "手里的钱为" + nowMoney); } }
  • 线程不安全的集合
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.wang.syn; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; /** * @author: 王海新 * @Date: 2021/3/3 09:22 * @Description: 线程不安全的集合 * 造成数据不是10000个的原因有两个 *因循环已经跑完,程序结束,线程还没有将数据加入的情况。 * 两个线程同时操作同一个位置,造成的数据覆盖。 */ public class UnsafeList { public static void main(String[] args) { //创建一个集合 List<String> array = new ArrayList<String>(); //利用for循环,创建1000个线程向集合里面添加数据 for (int i = 0; i < 10000; i++) { new Thread( () -> { array.add(Thread.currentThread().getName()); }).start(); } try {//利用阻塞。去除掉因循环已经跑完,程序结束,线程还没有将数据加入的情况。导致数据不一致的原因 Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(array.size()); } }

总结:线程不安全的主要原因是 线程都有独自的内存空间。

最后

以上就是欣慰月亮最近收集整理的关于线程状态,优先级,守护线程基础详解的全部内容,更多相关线程状态内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(75)

评论列表共有 0 条评论

立即
投稿
返回
顶部