java多线程优先级的方法_Java多线程以及线程优先级
文章目錄
1 繼承Thread類多線程的實現獲取和設置線程名稱線程優先級
2 實現Runnable接口3 實現Callable接口4 使用線程池
1 繼承Thread類
多線程的實現
實現多線程只需要繼承Thread類即可,重寫run()方法,封裝需要被線程執行的代碼
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調用線程的run()方法
my2.start();
my3.start();
}
}
獲取和設置線程名稱
使用getName()方法獲取線程名稱
@Override
public void run() {
for (int i = 0; i < 11; i++) {
System.out.println(getName() + " " + i);
}
}
使用setName()方法設置線程名稱
my1.setName("HelloWorld");
線程優先級
getPriority() 返回線程優先級 setPriority() 設置線程優先級
優先級由低到高為 1-10 , 默認值為 5線程優先級高僅僅表示線程獲取CPU時間片的幾率高并不一定會等優先級高的線程執行完了才去執行優先級低的線程
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());? ? //返回線程優先級
my1.setPriority(10);? ? // 設置線程優先級
my2.setPriority(5);
my3.setPriority(1);
my1.start();
my2.start();
my3.start();
}
}
2 實現Runnable接口
雖然繼承Thread類實現多線程非常簡單,但是在實際開發中,java單繼承這一特性使得我們在需要繼承其他類的時候,多線程的實現就要依靠實現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);
}
}
}
/**
* 創建MyRunnable類的對象
* 創建Thread類的對象,將MyRunnable對象作為構造方法的參數
*/
public class MyRunnableTest {
public static void main(String[] args) {
Runnable r1 = new MyRunnable();
Thread t1 = new Thread(r1, "hello");? ? // 可以直接設置線程名稱
Thread t2 = new Thread(r1, "world");
t1.start();
t2.start();
}
}
方法2總結
沒有繼承Thread類,如果有需求可以繼承其他類適合多個相同程序的代碼去處理同一個資源的情況,把線程和程序的代碼、數據有效分離
3 實現Callable接口
重寫call()方法好處:有返回值,允許拋異常
4 使用線程池
減少創建新線程的時間,重復利用線程池中的線程,降低資源消耗,可有返回值。
總結
以上是生活随笔為你收集整理的java多线程优先级的方法_Java多线程以及线程优先级的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java计算器接口策略_Java 基础
- 下一篇: java c3p0 配置文件_关于最近一