日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

java多线程优先级的方法_Java多线程以及线程优先级

發(fā)布時(shí)間:2024/10/14 java 71 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java多线程优先级的方法_Java多线程以及线程优先级 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

1 繼承Thread類多線程的實(shí)現(xiàn)獲取和設(shè)置線程名稱線程優(yōu)先級

2 實(shí)現(xiàn)Runnable接口3 實(shí)現(xiàn)Callable接口4 使用線程池

1 繼承Thread類

多線程的實(shí)現(xiàn)

實(shí)現(xiàn)多線程只需要繼承Thread類即可,重寫run()方法,封裝需要被線程執(zhí)行的代碼

public class MyThread extends Thread {

@Override

public void run() {

for (int i = 0; i < 11; i++) {

System.out.println(i);

}

}

}

public class ThreadTest {

public static void main(String[] args) {

Thread my1 = new MyThread();

Thread my2 = new MyThread();

Thread my3 = new MyThread();

my1.start();? ? // 啟動線程,由JVM調(diào)用線程的run()方法

my2.start();

my3.start();

}

}

獲取和設(shè)置線程名稱

使用getName()方法獲取線程名稱

@Override

public void run() {

for (int i = 0; i < 11; i++) {

System.out.println(getName() + " " + i);

}

}

使用setName()方法設(shè)置線程名稱

my1.setName("HelloWorld");

線程優(yōu)先級

getPriority() 返回線程優(yōu)先級 setPriority() 設(shè)置線程優(yōu)先級

優(yōu)先級由低到高為 1-10 , 默認(rèn)值為 5線程優(yōu)先級高僅僅表示線程獲取CPU時(shí)間片的幾率高并不一定會等優(yōu)先級高的線程執(zhí)行完了才去執(zhí)行優(yōu)先級低的線程

public class ThreadTest {

public static void main(String[] args) {

Thread my1 = new MyThread();

Thread my2 = new MyThread();

Thread my3 = new MyThread();

System.out.println(my1.getPriority());? ? //返回線程優(yōu)先級

my1.setPriority(10);? ? // 設(shè)置線程優(yōu)先級

my2.setPriority(5);

my3.setPriority(1);

my1.start();

my2.start();

my3.start();

}

}

2 實(shí)現(xiàn)Runnable接口

雖然繼承Thread類實(shí)現(xiàn)多線程非常簡單,但是在實(shí)際開發(fā)中,java單繼承這一特性使得我們在需要繼承其他類的時(shí)候,多線程的實(shí)現(xiàn)就要依靠實(shí)現(xiàn)Runnable接口

public class MyRunnable implements Runnable {

@override

public void run() {? ? ? ? // 同樣重寫run()方法

for (int i = 0; i < 20; i++) {

System.out.println(Thread.currentThread().getName() + " " + i);

}

}

}

/**

* 創(chuàng)建MyRunnable類的對象

* 創(chuàng)建Thread類的對象,將MyRunnable對象作為構(gòu)造方法的參數(shù)

*/

public class MyRunnableTest {

public static void main(String[] args) {

Runnable r1 = new MyRunnable();

Thread t1 = new Thread(r1, "hello");? ? // 可以直接設(shè)置線程名稱

Thread t2 = new Thread(r1, "world");

t1.start();

t2.start();

}

}

方法2總結(jié)

沒有繼承Thread類,如果有需求可以繼承其他類適合多個(gè)相同程序的代碼去處理同一個(gè)資源的情況,把線程和程序的代碼、數(shù)據(jù)有效分離

3 實(shí)現(xiàn)Callable接口

重寫call()方法好處:有返回值,允許拋異常

4 使用線程池

減少創(chuàng)建新線程的時(shí)間,重復(fù)利用線程池中的線程,降低資源消耗,可有返回值。

總結(jié)

以上是生活随笔為你收集整理的java多线程优先级的方法_Java多线程以及线程优先级的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。