java while等待 yeild_Java中run(), start(), join(), wait(), yield(), sleep()的使用
run(), start(), join(), yield(), sleep()
這些是多線程中常用到的方法.
run(): 每個(gè)Thread中需要實(shí)現(xiàn)的方法, 如果直接調(diào)用的話, 會(huì)是和單線程一樣的效果, 要另起線程需要使用start().
start(): 新起線程調(diào)用run(). 主線程不等待直接往下執(zhí)行
join(): 如果有一個(gè)Thread a, 在a.start()后面(可以使用thread.isAlive()判斷). 使用a.join() 可以使主線程等待a執(zhí)行完. 如果同時(shí)有多個(gè)線程a, b, c, 而d需要等abc執(zhí)行完后才能執(zhí)行, 可以在d start之前使用a.join, b.join, c.join, 也可以把a(bǔ), b, c的start放到d的run方法里面, 使用a.join, b.join, c.join, 可以用參數(shù)設(shè)置timeout時(shí)間
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()));
}
}
使用的時(shí)候
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(): 沒發(fā)現(xiàn)有什么特別, 似乎是可以保證不同優(yōu)先級(jí)的線程不會(huì)搶先運(yùn)行
sleep(): 需要時(shí)間作為參數(shù), 可以被interrupt.
wait() and notify(): 和join()的區(qū)別是, 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();
}
}
}
}
總結(jié)
以上是生活随笔為你收集整理的java while等待 yeild_Java中run(), start(), join(), wait(), yield(), sleep()的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 甩脂机能减肥吗
- 下一篇: 减肥喝水时间表是什么