線程的常用方法


一.Thread類的常用方法:

1.start():啟動當前線程並調用線程的run()方法
2.run():將創建線程要執行的操作聲明在此
3.currentThread():靜態方法,放回當前代碼執行的線程
4.getName():獲取當前線程的名字
5.setName():設置當前線程的名字
6.yield():釋放當前cpu的執行權
7.join():在線程A中調用線程B的join方法,使得線程A進入阻塞狀態,直到線程B完全執行完,線程A才結束阻塞狀態
8.stop():已過時,在執行此方法時,強制結束該線程
9.sleep(long long millis):讓當前線程睡眠指定的millis毫秒時間內(睡眠即當前線程為阻塞狀態)
10.isAlive():判斷當前線程是否還存活

代碼示例:

 1 class HelloThread extends Thread {
 2     public void run() {
 3         for (int i = 0; i <= 100; i += 2) {
 4             System.out.println(Thread.currentThread().getName() + ":" + i);
 5             if (i % 20 == 0) {
 6                 try {
 7                     sleep(1000);
 8                 } catch (InterruptedException e) {
 9                     throw new RuntimeException(e);
10                 }
11                 this.yield();
12             }
13         }
14     }
15 
16     public HelloThread() {
17         super();
18     }
19 
20     public HelloThread(String name) {
21         super(name);
22     }
23 }
24 
25 public class ThreadMethodTest {
26     public static void main(String[] args) {
27         //命名方法1
28         HelloThread h1 = new HelloThread();
29         h1.setName("線程1");
30         h1.start();
31         //命名方法2
32         HelloThread h2 = new HelloThread("線程2");
33         h2.start();
34         //給主線程命名
35         Thread.currentThread().setName("主線程");
36         for (int i = 1; i < 100; i += 2) {
37             System.out.println(Thread.currentThread().getName() + ":" + i);
38             if (i == 21) {
39                 try {
40                     h1.join();
41                 } catch (InterruptedException e) {
42                     throw new RuntimeException(e);
43                 }
44             }
45         }
46         System.out.println(Thread.currentThread().getName());
47         System.out.println(h1.isAlive());
48     }
49 
50 }

 

二.線程的優先級:

1.
MAX_PRIORITY:10
MIN_PRIORITY:1
NORM_PRIORITY:5
2.設置和獲取優先級
getPriority():獲取線程的優先級
setPriority(int p):設置線程的優先級

3.高優先級意味着有更高的概率被執行,並不意味着一定是高優先級的線程全部執行完后才執行低優先級的

1 //設置線程的優先級
2         h1.setPriority(10);
3         Thread.currentThread().setPriority(Thread.NORM_PRIORITY);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM