Thread类中的常用方法及线程的优先级

* 测试Thread类中的常用方法:
* 1.start() :启动当前线程;调用当前线程的run()
* 2.run() :通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
* 3.currentThread():静态方法,返回代码当前执行的线程
* 4.getName():获取当前线程的名字
* 5.setName():设置当前线程的名字
* 6.yield():释放当前CPU的执行权
* 7.join():在线程a中调用线程b的join(),此时线程a就进入阻塞状态,直到线程b完全执行完以后,线程b才结束阻塞状态
* 8.stop():已过时。当执行此方法时,强制结束当前线程。
* 9.sleep(long millitime):让当前线程 “睡眠” 指定的millitime(毫秒)
* 10.isAlive():判断当前线程是否还存活
*
*
* 线程的优先级:
* 1.
* MAX_PRIORITY:10(最高)
* MIN_PRIORITY:1(最低)
* NORM_PRIORITY:5(默认)
*2.如何获取和设置当前线程的优先级
* getPriority()
* setPriority(int p)
*说明:高优先级的线程要抢占低优先级线程cpu的执行权,但是只是从概率上讲,高优先级的线程高概率被执行,并不意味着只有当高优先级
* 的线程执行完毕以后,低优先级的线程才执行。
*

 1 package com.atfu.java01;
 2 
 3 /**
 4  *
 5  * @author fu jingchao
 6  * @creat 2021/10/14-22:16
 7  */
 8 class MethodTest extends Thread{
 9 
10     @Override
11     public void run() {
12         for (int i = 0; i < 100; i++) {
13             if(i % 2 == 0){
14                 System.out.println(Thread.currentThread().getName() + ":" + i);
15             }
16             if(i % 20 == 0){
17                 yield();
18             }
19         }
20         System.out.println("线程一的优先级为:"+Thread.currentThread().getPriority());
21     }
22 }
23 
24 
25 
26 public class ThreadMethodTest {
27     public static void main(String[] args) {
28         MethodTest m1 = new MethodTest();
29         m1.setName("线程一");
30         m1.start();
31 
32         //给主线程命名
33         Thread.currentThread().setName("主线程");
34         for (int i = 0; i < 100; i++) {
35             if(i % 2 == 0){
36                 System.out.println(Thread.currentThread().getName() + ":" + i);
37             }
38             if(i == 20){
39                 try {
40                     m1.join();
41                 } catch (InterruptedException e) {
42                     e.printStackTrace();
43                 }
44             }
45         }
46         System.out.println("主线程的优先级为:"+Thread.currentThread().getPriority());
47     }
48 }

 



posted @ 2021-10-15 22:30  橘猫的夏天  阅读(246)  评论(0)    收藏  举报