{System.out.println("執行緒名稱="+Thread.currentThread().getName());},threadName);//set方法方式//thread.setName"/> {System.out.println("執行緒名稱="+Thread.currentThread().getName());},threadName);//set方法方式//thread.setName">

首頁  >  文章  >  Java  >  Java執行緒常用的操作有哪些?

Java執行緒常用的操作有哪些?

WBOY
WBOY轉載
2023-04-24 11:55:07855瀏覽

執行緒的常用操作

設定執行緒名字:setName()

取得執行緒名稱:getName()

#執行緒唯一Id:getId()

// 自定义线程名称
String threadName = "threadName";
// 构造方法方式
Thread thread = new Thread(() -> {
    System.out.println("线程名=" + Thread.currentThread().getName());
},threadName);
// set方法方式
// thread.setName(threadName);
System.out.println("线程唯一Id=" + thread.getId());

執行緒啟動:start()

判斷執行緒是否存活:isAlive()

// 线程启动
thread.start();
System.out.println("是否为存活线程=" + thread.isAlive());

執行緒方法:run() /call()

執行緒啟動後會去呼叫的方法。執行緒要做什麼就在run/call方法寫,不需要直接調用,執行緒啟動後自己會去調用run() /call()。如果程式沒有啟動執行緒直接呼叫run/call,那麼就不屬於多執行緒編程,是屬於目前執行緒直接呼叫普通方法一樣。

取得目前執行緒物件:currentThread()

操作目前執行緒的非static方法,得先拿到執行緒物件才可以

// 获取当前线程对象
Thread currentThread = Thread.currentThread();
// 对当前线程做一些操作
System.out.println(currentThread.getName());
try {
    // sleep 静态方法则不需要
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

關於執行緒的狀態控制(生命週期)的操作可以參考上一篇文章。

守護線程(後台線程)

普通線程(使用者線程)的守護者,守護線程的任務是為其他的線程提供服務。如果進程中沒有了使用者線程,那麼守護線程也就沒有存在的意義,JVM也隨之結束。典型的守護線程有JVM的垃圾回收線程,作業系統的啟動也會啟動各種模組的守護線程。

設定執行緒為守護執行緒:setDaeman()

注意:該方法必須在start() 方法之前呼叫

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        System.out.println("线程名="+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 这一句不会打印出来,因为main线程(目前唯一的普通线程)等待1秒后已经结束了
        System.out.println("守护线程的状态=" + Thread.currentThread().getState());
    });
    // 守护线程
    thread.setDaemon(true);
    // 线程启动
    thread.start();
    System.out.println("是否为守护线程=" + thread.isDaemon());
}

執行緒串列化

執行join() 方法的執行緒進入等待喚醒狀態(WAITING),直到呼叫該方法的執行緒結束後再由等待喚醒狀態轉為可運行狀態(RUNNABLE)。 join() 方法是Thread類別中的方法,其底層是使用wait() 方法來實作執行緒等待,待執行緒isAlive()為false 時才

實作執行緒的串列化:一個執行緒呼叫另一個線程物件的join() 來實現線程串行化執行。

舉個例子:一道好菜

public class DemoCooking {
    
    public static void main(String[] args) {
        Thread mainThread = Thread.currentThread();
        // 1.买菜
        Thread buyThread = new Thread(new CookingThread(mainThread,"买菜"),"buyThread");
        // 2.洗菜
        Thread washThread = new Thread(new CookingThread(buyThread,"洗菜"),"washThread");
        // 3.切菜
        Thread cutThread = new Thread(new CookingThread(washThread,"切菜"),"cutThread");
        // 4.炒菜
        Thread scrambleThread = new Thread(new CookingThread(cutThread,"炒菜"),"scrambleThread");

        // 不受线程启动顺序的影响
        scrambleThread.start();
        washThread.start();
        cutThread.start();
        buyThread.start();
        
        // main线程先执行完才可以开始:买菜
        System.out.println("开始准备……");
    }

    public static class CookingThread implements Runnable{
        private final Thread thread;
        private final String job;

        public CookingThread(Thread thread, String job){
            this.thread = thread;
            this.job = job;
        }
        @Override
        public void run() {
            String name = Thread.currentThread().getName()+":";
            try {
                thread.join();

                System.out.println(name + job + "开始");
                Thread.sleep(1000);
                System.out.println(name + job + "结束");
                Thread.sleep(1000); // 偷懒下
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

執行結果:main > buyThread > washThread > cutThread > scrambleThread > 結束

開始準備……
buyThread:買菜開始
buyThread:買菜結束
washThread:洗菜開始
washThread:洗菜結束
cutThread:切菜開始
cutThread:切菜結束
scrambleThread:炒菜開始
scrambleThread:炒菜結束

執行緒優先權

設定目前執行緒的優先權,執行緒優先權越高,執行緒可能獲得執行的次數越多,Java執行緒的優先權以整數表示,優先權的範圍為1-10,預設為5。

setPriority(int)方法:設定執行緒的優先權。

getPriority方法:取得執行緒的優先權。

public static void main(String[] args) {

    Thread thread = new Thread(() -> {
        System.out.println("线程1");
    });
    thread.setPriority(10);
    Thread thread1 = new Thread(() -> {
        System.out.println("线程2");
    });
    thread1.setPriority(1);
    thread.start();
    thread1.start();

    System.out.println("线程默认的优先级为=" + Thread.currentThread().getPriority());

}

執行緒中斷

使用interrupt() 方法設定執行緒中斷標誌=true,讓執行緒受到「阻塞」時拋出一個中斷訊號。如果執行緒處於阻塞、等待喚醒或超時等待狀態(Object.wait, Thread.join和Thread.sleep)時,那麼它將接收到一個中斷異常(InterruptedException),從而提前被結束該狀態。反之,如果執行緒是處於「可運行」(RUNNABLE)狀態,那麼中斷標誌將沒有作用。

案例一:執行緒中斷有效

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        System.out.println("线程1");
        try {
            // 闹钟1分钟后响
            Thread.sleep(60000);
            System.out.println("闹钟响了");
        } catch (InterruptedException e) {
            // 提前退出超时等待状态
            System.out.println("发生异常,提前醒了,闹钟没响手动关了");
        }

        System.out.println("继续执行该线程的后续程序……");

    });
    thread.setPriority(1);
    thread.start();
    thread.interrupt();
    System.out.println("main线程将thread 终端状态设置为 "+thread.isInterrupted());
}

執行結果:

#main執行緒將thread 終端機狀態設為true
執行緒1
發生異常,提前醒了,鬧鐘沒響手動關了
繼續執行該線程的後續程序……

##案例二:線程中斷無效

public static void main(String[] args) {
    Thread thread1 = new Thread(() -> {
        System.out.println("线程" + Thread.currentThread().getName());
        while (true) {
            System.out.print(Thread.currentThread().getState() + "\t");
        }
    });
    thread1.start();
    thread1.interrupt();
}

執行結果:執行緒一直列印自己的狀態為RUNNABLE。

以上是Java執行緒常用的操作有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除