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()的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 甩脂机能减肥吗
- 下一篇: java美元兑换,(Java实现) 美元