线程礼让
概念
礼让线程,让当前正在执行的线程暂停,但不阻塞 将线程从运行状态转为就绪状态 让cpu重新调度,礼让不一定成功!看CPU心情
代码:测试礼让线程
public class TestYield {
public static void main ( String [ ] args) {
MyYield myYield = new MyYield ( ) ;
new Thread ( myYield, "a" ) . start ( ) ;
new Thread ( myYield, "b" ) . start ( ) ;
}
}
class MyYield implements Runnable {
@Override
public void run ( ) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "线程开始执行!" ) ;
Thread . yield ( ) ;
System . out. println ( Thread . currentThread ( ) . getName ( ) + "线程停止执行!" ) ;
}
}
Join
概念
Join合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞 可以想象成插队
代码:测试join方法
public class TestJoin implements Runnable {
public static void main ( String [ ] args) throws InterruptedException {
TestJoin testJoin = new TestJoin ( ) ;
Thread thread = new Thread ( testJoin)
thread. start ( ) ;
for ( int i = 0 ; i< 1000 ; i++ ) {
if ( i== 200 ) {
thread. join ( ) ;
}
System . out. println ( "main" + i) ;
}
}
@Override
public void run ( ) {
for ( int i = 0 ; i< 100 ; i++ ) {
System . out. println ( "线程VIP来了" + i) ;
}
}
}