首页 > 技术文章 > 测试Thread中的常用方法

yhqtv-com 2020-04-28 13:07 原文

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

 

推荐阅读