线程的sleep、join、yield、wait步骤
线程的sleep、join、yield、wait方法
sleep方法:可以调用Thread的静态方法 public static void sleep(long millis) throws InterruptedException 使得当前线程休眠(暂停执行millis毫秒)、由于是静态方法,sleep可以由类名直接调用:Thread.sleep()
wait 与 sleep区别:wait时别的线程可以访问锁定对象——调用wait方法时必需锁定该对象、sleep时别的线程也不可以访问锁定对象
join方法:合并某个线程
yield方法:让出CPU,给其他线程执行的机会
sleep方法:可以调用Thread的静态方法 public static void sleep(long millis) throws InterruptedException 使得当前线程休眠(暂停执行millis毫秒)、由于是静态方法,sleep可以由类名直接调用:Thread.sleep()
wait 与 sleep区别:wait时别的线程可以访问锁定对象——调用wait方法时必需锁定该对象、sleep时别的线程也不可以访问锁定对象
import java.util.*; public class TestInterrupt { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // 继承与Thread类,可以直接调用start()启动线程 try { Thread.sleep(10000); // 在主线程中调用sleep,主线程则sleep } catch (InterruptedException e) { } thread.shutDown(); // 结束子线程 // thread.interrupt(); //调用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; } } } public void shutDown() { flag = false; } }
join方法:合并某个线程
public class TestJoin { public static void main(String[] args) { MyThread2 t1 = new MyThread2("abcde"); // 给t1取个名字 t1.start(); // t1产生一个分支线程 try { t1.join(); // 合并线程,则只有一个线程,按顺序执行 } catch (InterruptedException e) { } 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; } } } }
yield方法:让出CPU,给其他线程执行的机会
public class TestYield { public static void main(String[] args) { MyThread3 t1 = new MyThread3("t1");// 同一线程new两对象,共3条线程 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) { // 每到10的倍数则切换线程 yield(); } } } }