join合并线程
public class JoinThread {
public static void main(String args[]) throws InterruptedException {
Thread t = new Thread(new MyThread());
t.start();
for(int i =0;i<1000;i++){
if(i == 10){
t.join(); // main方法阻塞 必须等待 t执行完毕, join合并线程
}
System.err.println("main...."+i);
}
}
}
class MyThread implements Runnable{
@Override
public void run() {
for(int i =0;i<50;i++){
System.err.println("myThread...."+i);
}
}
}
yield Thread.yield() 阻塞当前线程
public class YieldThread {
public static void main(String args[]) throws InterruptedException {
Thread t = new Thread(new MyThread1());
t.start();
for(int i =0;i<1000;i++){
if(i%20 == 0 ){
Thread.yield(); // main方法 阻塞自己,主要取决于cpu
}
System.err.println("main...."+i);
}
}
}
class MyThread1 implements Runnable{
@Override
public void run() {
for(int i =0;i<50;i++){
System.err.println("yield...."+i);
}
}
}
sleep 休眠,不会释放锁