Thread中的常用方法

 1 package day2_3;
 2 
 3 /**
 4  * 测试Thread中的常用方法
 5  * 1.start() 启动当前线程,调用当前线程的run()
 6  * 2.run()   通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
 7  * 3.currentThread()  静态方法,返回执行当前代码的线程
 8  * 4.getName()  获取当前线程的名字
 9  * 5.setName()  设置当前线程的名字
10  * 6.yield()    释放当前cup的执行权
11  * 7.join()     在线程A中调用线程B的join(),此时线程A就进入阻塞状态,直到线程B完全执行完以后,
12  *              线程A才结束阻塞状态
13  * 8.stop()     已过时,当执行此方法时,强制结束当前线程
14  * 9.sleep(long millitime)  静态方法,让当前线程睡眠指定的millitime毫秒,在指定的millitime毫秒时间内,
15  *              当前线程是阻塞状态
16  * 10.isAlive()  判断当前线程是否存活(线程的run()是否执行完)
17  *
18  *
19  * 程序的优先级
20  * 1.
21  * MAX_PRIORITY = 10
22  * MIN_PRIORITY = 1
23  * NORM_PRIORITY = 5  ---->默认优先级
24  * 2.如何获取和设置当前线程的优先级
25  *   getPriority()
26  *   setPriority(int p)
27  *     说明:高优先级的线程要抢占低优先级线程cup的执行权。但是只是从概率上讲,高优先级的线程高概率
28  *     的情况下被执行,并不意味着只有当高优先级的线程执行完以后,低优先级线程才执行
29  *
30  *
31  *
32  *
33  *
34  *
35  * @Author Tianhao
36  * @create 2021-02-03-22:14
37  */
38 
39 class HelloThread extends Thread {
40     @Override
41     public void run() {
42         for (int i = 0; i < 100; i++) {
43             if (i % 2 == 0) {
44                 System.out.println(getName() + ": "
45                         + Thread.currentThread().getPriority() + ": " +  i);
46             }
47 
48             if (i%20 ==0) {
49                 yield();
50             }
51         }
52     }
53 
54     //线程命名方式二:声明带参构造器,并调用父类的带参构造器
55     public HelloThread(String name) {
56         super(name);
57     }
58 
59 }
60 
61 
62 public class ThreadMethodTest {
63     public static void main(String[] args) {
64         //使用带参构造器命名线程
65         HelloThread h1 = new HelloThread("新线程");
66         //线程命名方式一
67 //        thread.setName("线程一");
68         h1.setPriority(Thread.MAX_PRIORITY);
69         h1.start();
70 
71         //给主线程命名
72         Thread.currentThread().setName("主线程");
73 
74         Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
75         for (int i = 0; i < 100; i++) {
76             if (i % 2 == 0) {
77 //                try {
78 //                    Thread.currentThread().sleep(10);
79 //                } catch (InterruptedException e) {
80 //                    e.printStackTrace();
81 //                }
82                 System.out.println(Thread.currentThread().getName() + ": "
83                         + Thread.currentThread().getPriority() + ": " + i);
84             }
85 
86 //            if (i == 20) {
87 //                try {
88 //                    h1.join();
89 //                } catch (InterruptedException e) {
90 //                    e.printStackTrace();
91 //                }
92 //            }
93 
94             System.out.println(h1.isAlive());
95         }
96     }
97 }

 

posted @ 2021-02-05 14:04  dog_IT  阅读(211)  评论(0编辑  收藏  举报