join,sleep,yield这三个分别在多线程中是起到什么作用的?
知道的朋友,请说的详细些:)

解决方案 »

  1.   

    join方法:假如你在A线程中调用了B线程的join方法(B.join();),这时B线程继续运行,A线程停止(进入阻塞状态)。等B运行完毕A再继续运行,中途B线程不受影响。这里要注意的是A先成停止的位置就在调用join方法处,后面代码不执行,要等B完了以后再执行。
    sleep方法和yield方法要做个比较!线程中调用sleep方法后,本线程停止(进入阻塞状态),运行权交给其他线程。而线程中调用yield方法后本线程并不停止,运行权又本线程和优先级不低与本线程的线程来抢(这里要注意并不是优先级低的就一定抢不过优先级高的,优先级高的只是时间片大一些)。
      

  2.   

    关于这三个  去机子上一测试 什么都明白,光听不动手 肯定模糊
    1.sleep
    static void sleep(long millis)  
    sleep方法是静态方法,说明类Thread可以调用。
    sleep举例:
    import java.util.*;
    public class TestInterrupt {
      public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();                          
        try {Thread.sleep(10000);}    //主线程睡10秒。
        catch (InterruptedException e) {}
        thread.interrupt();
      }
    }class MyThread extends Thread {
     boolean flag = true;
      public void run(){
        while(flag){
          System.out.println("==="+new Date()+"===");
          try {
            sleep(1000);
          } catch (InterruptedException e) {
            return;
          }
        }
      }
    }2.join可并某个线程
    public class TestJoin {
      public static void main(String[] args) {
        MyThread2 t1 = new MyThread2("abcde");
        t1.start();
        try {
         t1.join();                                       //本来运行完t1.start之后,就会出现主线程和t1线程并行的运行。
        } catch (InterruptedException e) {}//但是join后,t1线程合并到主线程,主线程等t1运行完后再运行。
         
        for(int i=1;i<=10;i++){
          System.out.println("i am main thread");
        }
      }
    }
    class MyThread2 extends Thread {
      MyThread2(String s){
       super(s);
      }
      
      public void run(){
        for(int i =1;i<=10;i++){
          System.out.println("i am "+getName());
          try {
           sleep(1000);
          } catch (InterruptedException e) {
           return;
          }
        }
      }
    }
    3.yield方法
    让出CPU,给其他线程运行的机会。public class TestYield {
      public static void main(String[] args) {
        MyThread3 t1 = new MyThread3("t1");
        MyThread3 t2 = new MyThread3("t2");
        t1.start(); t2.start();
      }
    }
    class MyThread3 extends Thread {
      MyThread3(String s){super(s);}
      public void run(){
        for(int i =1;i<=100;i++){
          System.out.println(getName()+": "+i);
          if(i%10==0){
            yield();
          }
        }
      }
    }