Java线程中yield与join方法的区别

版权声明:你好,欢迎来到我的博客。 https://blog.csdn.net/zwyjg/article/details/73657548



public class HufanTest extends Thread {
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new MyThread1();
		t1.start();

		for (int i = 0; i < 20; i++) {
			System.out.println("主线程第" + i + "次执行!");
			if (i > 2){
				try {
					// t1线程合并到主线程中,主线程停止执行过程,转而执行t1线程,直到t1执行完毕后继续。
					t1.join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

class MyThread1 extends Thread {
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println("线程1第" + i + "次执行!");
		}
	}
}

暂停当前正在执行的线程对象。

程序创建了名为生产者和消费者的两个线程,前者最小优先级,后者最大优先级。调用yield方法,两个线程会依次打印,然后将执行机会交给对方,一直这样进行下去。如果不加yield,结果是先打印完一个,再是另一个

public class Yield {

	public static void main(String[] args) {
		Thread producer = new Producer();  
        Thread consumer = new Consumer();  
          
        producer.setPriority(Thread.MIN_PRIORITY);  
        consumer.setPriority(Thread.MAX_PRIORITY);  
          
        producer.start();  
        consumer.start();  
	}
}
class Producer extends Thread  {  
    public void run()  {  
        for(int i = 0; i < 5; i++)  {  
            System.out.println("i am producer: producerd item " + i);  
            Thread.yield();  
        }  
    }  
}  
  
class Consumer extends Thread  {  
    public void run()  {  
        for(int i = 0; i < 5; i++)  {  
            System.out.println("i am Consumer: Consumed item " + i);  
            Thread.yield();  
        }  
    }  
}  


猜你喜欢

转载自blog.csdn.net/zwyjg/article/details/73657548