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);
- 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 : 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();
- }
- }
- }
线程中一些常用方法的分析
原文:http://www.cnblogs.com/yaobolove/p/5472131.html