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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java while等待 yeild_Java中run(), start(), join(), wait(), yield(), sleep()的使用

發布時間:2023/12/4 java 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java while等待 yeild_Java中run(), start(), join(), wait(), yield(), sleep()的使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

run(), start(), join(), yield(), sleep()

這些是多線程中常用到的方法.

run(): 每個Thread中需要實現的方法, 如果直接調用的話, 會是和單線程一樣的效果, 要另起線程需要使用start().

start(): 新起線程調用run(). 主線程不等待直接往下執行

join(): 如果有一個Thread a, 在a.start()后面(可以使用thread.isAlive()判斷). 使用a.join() 可以使主線程等待a執行完. 如果同時有多個線程a, b, c, 而d需要等abc執行完后才能執行, 可以在d start之前使用a.join, b.join, c.join, 也可以把a, b, c的start放到d的run方法里面, 使用a.join, b.join, c.join, 可以用參數設置timeout時間

class JoiningThread extends Thread {

// NOTE: UNTESTED!

private String name;

private Thread nextThread;

public JoiningThread(String name) {

this(name, null);

}

public JoiningThread(String name, Thread other) {

this.name = name;

this.nextThread = other;

}

public String getName() {

return name;

}

@Override

public void run() {

System.out.println("Hello I'm thread ".concat(getName()));

if (nextThread != null) {

while(nextThread.isAlive()) {

try {

nextThread.join();

} catch (InterruptedException e) {

// ignore this

}

}

}

System.out.println("I'm finished ".concat(getName()));

}

}

使用的時候

public static void main(String[] args) {

Thread d = WaitingThread("d");

Thread c = WaitingThread("c", d);

Thread b = WaitingThread("b", c);

Thread a = WaitingThread("a", b);

a.start();

b.start();

c.start();

d.start();

try {

a.join();

} catch (InterruptedException e) {}

}

yield(): 沒發現有什么特別, 似乎是可以保證不同優先級的線程不會搶先運行

sleep(): 需要時間作為參數, 可以被interrupt.

wait() and notify(): 和join()的區別是, wait需要額外的notify來終止, 上面的類可以改寫為

class WaitingThread extends Thread {

// NOTE: UNTESTED!

private Thread previousThread;

private String name;

public WaitingThread(String name) {

this(name, null);

}

public WaitingThread(String name, Thread other) {

this.name = name;

this.previousThread = other;

}

public String getName() {

return name;

}

@Override

public void run() {

System.out.println("Hello I'm thread ".concat(getName()));

// Do other things if required

// Wait to be woken up

while(true) {

synchronized(this) {

try {

wait();

break;

} catch (InterruptedException e) {

// ignore this

}

}

}

System.out.println("I'm finished ".concat(getName()));

// Wake up the previous thread

if (previousThread != null) {

synchronized(previousThread) {

previousThread.notify();

}

}

}

}

總結

以上是生活随笔為你收集整理的java while等待 yeild_Java中run(), start(), join(), wait(), yield(), sleep()的使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。