sleep:
sleep()方法是Thread类的一个静态方法,其作用是使当前线程暂停执行一段时间(可自定义暂停时长),让其他线程有机会执行,当调用Thread.sleep()方法后,若有同步代码块(synchronized)该线程不会释放对象锁(排他锁),其他线程无法访问共享数据。
demo:
public class SleepTest {
public static void main(String[] args) throws Exception {
TestThread r1=new TestThread();
Thread t1=new Thread(r1);
Thread t2=new Thread(r1);
t1.start();
t2.start();
}
}
class TestThread implements Runnable{
public Object object=new Object();
@Override
public void run() {
synchronized(object){
System.out.println("Thread is running......");
try {
Thread.sleep(3000);
System.out.println("Thread end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
结果:
Thread is running......
Thread end
Thread is running......
Thread end
仅当第一个线程执行3s完成之后,第二个线程才会开始执行
当去掉同步块之后:
public void run() {
//synchronized(object){
System.out.println("Thread is running......");
try {
Thread.sleep(3000);
System.out.println("Thread end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//}
其结果为:
Thread is running......
Thread is running......
Thread end
Thread end
两个线程几乎同时完成执行
yield:
该方法与sleep()类似,只是不能由用户指定暂停多长时间,并且yield()方法只能让同优先级的线程有执行的机会。线程执行sleep()方法后转入阻塞(blocked)状态,而执行yield()方法后转入就绪(ready)状态。
join:
thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。
比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
源码:
/**
* Waits at most <code>millis</code> milliseconds for this thread to
* die. A timeout of <code>0</code> means to wait forever.
*/
public final synchronized void join(long millis) throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
Join方法实现是通过wait(小提示:Object 提供的方法)。 当main线程调用t.join时候,main线程会获得线程对象t的锁(wait 意味着拿到该对象的锁),调用该对象的wait(等待时间),直到该对象唤醒main线程 ,比如退出后。这就意味着main 线程调用t.join时,必须能够拿到线程t对象的锁。
join方法的具体理解可参照该博客:
http://blog.youkuaiyun.com/FG2006/article/details/6393768
本文详细介绍了Java中用于线程控制的三种方法:sleep(), yield()和join()。通过实例演示了这些方法如何影响线程的执行顺序及状态转换,并对比了它们之间的差异。
489

被折叠的 条评论
为什么被折叠?



