线程中一些常用方法的分析

join() :

在一个线程中调用另一个线程的join(),则当前线程阻塞,让另一个线程先执行后,当前才执行.   根优先级无关.
从某种意义上来说,要两个线程都执行这个方法才有作用

      

package Test1;

public class test7 {

	public static void main(String[] args) throws InterruptedException {
		MyThread1 mt=new MyThread1();
		MyThread mt1=new MyThread();
		Thread t=new Thread(mt);
		Thread t1=new Thread(mt1);
		t.start();
		t.join();
		t1.start();
		t1.join();
		

	}

}

 class MyThread1 implements Runnable{
	 int i=1;
	@Override
	public void run() {
		while(true && i<=10){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			i++;
			System.out.println("This is Thread");
		}
		
		
	}
	
}


yeild() :

这个方法的作用就是:暂停当前正在执行的线程对象,并执行其他线程 ,和sleep,join方法有点类似

yield与sleep的区别:
1. sleep给其它线程运行的机会,但不考虑其它线程的优先级;但yield只会让位给相同或更高优先级的线程;
2. sleep有异常, yield没有
3.  当线程执行了sleep方法后,将转到阻塞状态,而执行了yield方法之后,则转到就绪状态;




yield与join的区别:
1. yield是静态方法, join是实例方法
2. yield只会让位给相同或更高优先级的线程, join无优先级无关


package Test1;
 
public class test8
{
   public static void main(String[] args)
   {
      Thread producer = new Producer();
      Thread consumer = new Consumer();
 
      producer.setPriority(Thread.MIN_PRIORITY); //Min Priority
      consumer.setPriority(Thread.MAX_PRIORITY); //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 : Produced 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();
      }
   }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值