⒈ 寫一個冒泡排序方法
【參考答案】
publicstaticvoid?Bubble(int?a[]){for?(int?i?=?0;?i?<?a.length;?i++)?{for?(int?j?=?a.length-1;?j>i;j++)?{if?(a[j]
⒉ 子線程循環(huán)10次,接著主線程循環(huán)100,接著又回到子線程循環(huán)10次,接著再回到主線程又循環(huán)100,如此循環(huán)50次,請寫出程序。
publicclass?ThreadTest?{publicstaticvoid?main(String[]?args)?{new?ThreadTest().init();}publicvoid?init(){final?Business?business=new?Business();new?Thread(new?Runnable(){@Overridepublicvoid?run()?{for?(int?i?=?0;?i?<?50;?i++)?{business.SubThread(i);}}}).start();for?(int?i?=?0;?i?<?50;?i++)?{business.MainThread(i);}}privateclass?Business{booleanbShouldSub=true;//這里相當于定義了控制該誰執(zhí)行的一個信號燈publicsynchronizedvoid?MainThread(int?i){if?(bShouldSub)?{try?{this.wait();}?catch?(InterruptedException?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}for?(int?j?=?0;?j?<?5;?j++)?{System.err.println(Thread.currentThread().getName()+":i="+i+",j="+j);}bShouldSub=true;this.notify();}}publicsynchronizedvoid?SubThread(int?i1){if?(!bShouldSub)?{try?{this.wait();}?catch?(InterruptedException?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}for?(int?j?=?0;?j?<?10;?j++)?{System.err.println(Thread.currentThread().getName()+":i="+i1+",j="+j);}bShouldSub=false;this.notify();}}}}
備注:不可能一上來就寫出以上代碼,最初寫出來的代碼如下,問題在于兩個線程的代碼要參照同一個變量,即這兩個線程要共享數據,所以,把這兩個線程的執(zhí)行代碼搬到同一個類中區(qū):
publicclass?thread?{privatestaticbooleanbShouldMain=false;publicstaticvoid?main(String[]?args)?{//final?String?str?=new?String("");new?Thread(new?Runnable()?{publicvoid?run()?{for?(int?i?=?0;?i?<?50;?i++)?{synchronized?(Thread.class)?{if?(bShouldMain)?{try?{ThreadTest.class.wait();}?catch?(InterruptedException?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}}for?(int?j?=?0;?j?<?10;?j++)?{System.out.println(Thread.currentThread().getName()+":i="+i+",j="+j);}bShouldMain=true;ThreadTest.class.notify();}}}}).start();for?(int?i?=?0;?i?<?50;?i++)?{if?(!bShouldMain)?{try?{ThreadTest.class.wait();}?catch?(InterruptedException?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}}for?(int?j?=?0;?j?<5;?j++)?{System.out.println(Thread.currentThread().getName()+":i="+i+",j="+j);}bShouldMain=false;ThreadTest.class.notify();}}}
以上就是長沙中公優(yōu)就業(yè)java培訓機構的小編針對“面試常出現(xiàn)的Java上機練習題及答案”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為你服務。