Java中有几个方法经常看到,但大部分情况都比较少用到,这些方法包括Object类的wait(),notify(),Thread类的yield(),join(),还有sleep()。
wait方法
表示让出锁并等待,直到其它线程notify且竞争到锁为止,注意wait建议放在循环中而不是if语句中。为什么要放在while中呢?原因很简单:有时会出现wait被唤醒但condition仍为true的情况,此时需要重新调用wait让出锁继续等待。
final Object obj = new Object();
Thread t = new Thread(){
@Override
public void run() {
boolean condition = true;
synchronized (obj) {
try {
while(condition) {
obj.wait();
//要执行的代码
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
notify方法
通知正在wait的线程可以开始竞争锁了,线程调度器会随机选一个正在wait的线程出来,而如果是调用notifyAll方法则所有正在wait的线程会同时竞争该锁。注意当前线程notify后并不会马上让出锁,而需要执行完同步代码块才会让出锁。
Thread t = new Thread(){
@Override
public void run() {
synchronized (obj) {
//执行相关代码
obj.notifyAll();
//这些代码执行完才会让出锁
}
}
};
t.start();
yield方法
Thread的static方法,表示当前线程乐意让出CPU给其它相同线程优先级的线程用。
join方法
代码t.join()表示等待t线程执行完才继续执行调用处下面的代码。(其中t为一Thread对象),如下面的代码:
Thread t = new Thread() {
public void run() {
System.out.println("子线程开始执行了");
try {
Thread.sleep(3 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程执行完了");
}
};
t.start();
try {
t.join();//t线程执行完才会继续执行下去
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程执行完了");
结果打印:
子线程开始执行了
子线程执行完了
主线程执行完了
sleep方法
Thread类方法,表示当前休眠指定一段时间,它并不会让出当前拥有的锁。那么如果指定sleep时间为0呢?它跟yield有什么区别?来自stackoverflow:
No. The most obvious difference is that sleep() throws the (checked) InterruptedException. In practice, the effect may be almost the same, but it’s entirely implementation-dependant.
I’d wager that doing each a million times in a row would take much longer for sleep(), since system timer granularity probably often causes it to actually sleep for a non-negligible amount of time.
本博客已停止更新,转移到微信公众号上写文章,欢迎关注:Android进阶驿站