Java线程中yield与join方法的区别代码解析

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

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();  
        }  
    }  
}
原文地址: http://www.xz-src.com/6733.html
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值