4.yield()使线程让出CPU去执行相同优先级的其他程序,但是不会释放锁,(内部还是sleep)执行yield()之后该线程直接进入就绪状态再次参与竞争,生产中很少使用。
5.A线程的run()中调用了B线程的join(),则A线程等待B线程执行完之后,再继续执行,实际上调用了Object类中的wait()方法,会释放锁
public class ThreadJoin {
public static void main(String[] args) throws IOException {
System.out.println("进入线程"+Thread.currentThread().getName());
ThreadJoin test = new ThreadJoin();
MyThread thread1 = test.new MyThread();
thread1.start();
try {
System.out.println("线程"+Thread.currentThread().getName()+"等待");
thread1.join();
System.out.println("线程"+Thread.currentThread().getName()+"继续执行");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyThread extends Thread{
@Override
public void run() {
System.out.println("进入线程"+Thread.currentThread().getName());
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
// TODO: handle exception
}
System.out.println("线程"+Thread.currentThread().getName()+"执行完毕");
}
}
}
复制代码
输出:
进入线程main
线程main等待
进入线程Thread-0
线程Thread-0执行完毕
线程main继续执行 |