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();
}
}
}
}