Java 初学者-java多线程04
今天学习了java多线程关于线程睡眠操作的方法。
public class ThreadTest { public static void main(String[] args) { // TODO Auto-generated method stub Thread t = new Thread(new MyRunnable3()); t.setName("aaa"); t.start(); try { Thread.sleep(1500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 利用异常处理机制,终止线程的睡眠 t.stop();//这种方式直接将线程杀死,会丢失数据,不建议使用 for(int i=0;i<100;i++) { System.out.println(i); } // 会让其出异常 } } class MyRunnable3 implements Runnable { public void run() {// 这里不能throws因为子类不能比父类抛出更多更宽泛的异常 System.out.println(Thread.currentThread().getName() + "--->begin"); try { Thread.sleep(1500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // interrupt方法进入阻塞状态,使其放弃是、之前占有的cpu时间片 // 因此会回到主线程执行5秒后的程序 System.out.println(Thread.currentThread().getName() + "---->end"); for(int i=0;i<100;i++) { System.out.println("|"+i); } } }
明天计划学习java多线程。