线程的让位yield与合并join

//这里要知道yield是一个静态让位方法,什么意思呢?当有两个优先级相同的线程时可以通过yield给另一个线程让位,你可以自定义让位的条件,但是让位的时间是不确定的,定义了让为条件后在该条件下一定会让位但同样有可能在其他条件下也会让位,下面是代码,当一个数能整出20时便让位给主线程,这个条件是一定会执行的,但是并不意味着一定是20的整数倍才让位。见代码:

package ThreadTest;

class Processor09 implements Runnable{
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0; i<=100; i++){
			System.out.println(Thread.currentThread().getName() + "-->" + i);
			if(i%20 == 0){
				Thread.yield();
			}
		}
	}
}

public class ThreadTest09 {

	public static void main(String[] args) {
		
		Thread t = new Thread(new Processor09());
		t.setName("t");
		t.start();
		for(int i=0; i<=100; i++){
			System.out.println(Thread.currentThread().getName() + "-->" + i);
		}
	}
}

//下面是线程的合并,用的是join方法,这个方法是一个成员方法,当一个线程a用了该方法,该方法在那个线程中那么a和哪个线程合并,此时两个栈空间变成了一个栈空间。见代码:

package ThreadTest;

class Processor10 implements Runnable{
	@Override
	public void run() {
		// TODO Auto-generated method stub
	
		for(int i=0; i<5; i++){
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				// TODO: handle exception
			}
			System.out.println(Thread.currentThread().getName() + "-->" + i);
		}
	}
}

public class ThreadTest10 {

	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new Processor10());
		t.setName("T");
		t.start();
		t.join();
		for(int i=0; i<10; i++){
			System.out.println(Thread.currentThread().getName() + "-->" + i);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/small__snail__5/article/details/81304017