性格决定命运,气度影响格局
posts - 20, comments - 18, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

sleep、join、yield举例

Posted on 2007-08-01 20:03 尚爱军 阅读(336) 评论(0)  编辑  收藏

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();
      }
    }
  }
}

只有注册用户登录后才能发表评论。


网站导航: