package com.ljl.org.test4; /** *@DEMO:Interview *@Author:jilongliang *@Date:2013-4-17 * * 分別使用Runnable接口和Thread類編程實 編寫一應用程序建立兩個線程一個線程打印輸出1—1000之間全部的奇數(Odd Number) * 另一個線程打印輸出1-1000之間全部的偶數(Even Number)要求兩個線程隨機休眠一 段時間後 繼續打印輸出下一個數 * * 建立線程有兩種方式: 1.實現Runnable接口 2.繼承Thread類 * 實現方式和繼承方式有啥區別? * 實現方式的好處:避免了單繼承的侷限性 在定義線程時. * 建議使用實現方式 * 區別: * 繼承Thread:線程代碼存放Thread子類run方法中 實現 * Runnable:線程代碼存放接口的子類的run方法 * wait釋放資源,釋放鎖 * sleep釋放資源,不釋放鎖 */ @SuppressWarnings("all") public class Thread1 { public static void main(String[] args) { //方法一 /* OddNumber js = new OddNumber(); js.start(); EvenNumber os = new EvenNumber(); os.start(); while (true) { if (js.i1 == 1000 || os.i2 == 1000) { System.exit(-1); } } */ //方法二 OddNum on=new OddNum(); EvenNum en=new EvenNum(); new Thread(on).start(); new Thread(en).start(); while (true) { if (on.i1 == 1000 || en.i2 == 1000) { System.exit(-1); } } } } /** * ============================繼承Thread的線程=============================== */ class EvenNumber extends Thread { int i2; @Override public void run() { for (i2 = 1; i2 <= 1000; i2++) { if (i2 % 2 == 0) { System.out.println("偶數" + i2); } try { sleep((int) (Math.random() * 500) + 500); } catch (Exception e) { } } } } class OddNumber extends Thread { int i1; @Override public void run() { for (i1 = 1; i1 <= 1000; i1++) { if (i1 % 2 != 0) { System.out.println("奇數" + i1); } try { sleep((int) (Math.random() * 500) + 500); } catch (Exception e) { } } } } /** * ============================實現Runnable的線程=============================== */ @SuppressWarnings("all") class OddNum implements Runnable { int i1; @Override public void run() { for (i1 = 1; i1 <= 1000; i1++) { if (i1 % 2 != 0) { System.out.println("奇數" + i1); } try { new Thread().sleep((int) (Math.random() * 500)+500); } catch (Exception e) { } } } } @SuppressWarnings("all") class EvenNum implements Runnable { int i2; @Override public void run() { for (i2 = 1; i2 <= 1000; i2++) { if (i2 % 2 == 0) { System.out.println("偶數" + i2); } try { /**在指定的毫秒數內讓當前正在執行的線程休眠 * Math.random()一個小於1的隨機數乘於500+500,隨眠時間不會超過1000毫秒 */ //new Thread().sleep((int) (Math.random() * 500)+500); new Thread().sleep(1000);//也能夠指定特定的參數毫秒 } catch (Exception e) { } } } }