更新時間:2020-08-19 15:57:42 來源:動力節點 瀏覽2423次
⒈ 寫一個冒泡排序方法
【參考答案】
publicstaticvoid?Bubble(int?a[]){
for?(int?i?=?0;?i?<?a.length;?i++)?{
for?(int?j?=?a.length-1;?j>i;j++)?{
if?(a[j]
⒉ 子線程循環10次,接著主線程循環100,接著又回到子線程循環10次,接著再回到主線程又循環100,如此循環50次,請寫出程序。
publicclass?ThreadTest?{
publicstaticvoid?main(String[]?args)?{
new?ThreadTest().init();
}
publicvoid?init(){
final?Business?business=new?Business();
new?Thread(
new?Runnable(){
@Override
publicvoid?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;//這里相當于定義了控制該誰執行的一個信號燈
publicsynchronizedvoid?MainThread(int?i){
if?(bShouldSub)?{
try?{
this.wait();
}?catch?(InterruptedException?e)?{
//?TODO?Auto-generated?catch?block
e.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?block
e.printStackTrace();
}
for?(int?j?=?0;?j?<?10;?j++)?{
System.err.println(Thread.currentThread().getName()+":i="+i1+",j="+j);
}
bShouldSub=false;
this.notify();
}
}
}
}
備注:不可能一上來就寫出以上代碼,最初寫出來的代碼如下,問題在于兩個線程的代碼要參照同一個變量,即這兩個線程要共享數據,所以,把這兩個線程的執行代碼搬到同一個類中區:
publicclass?thread?{
privatestaticbooleanbShouldMain=false;
publicstaticvoid?main(String[]?args)?{
/*new?Thread(){
public?void?run()?{
for?(int?i?=?0;?i?<?50;?i++)?{
for?(int?j?=?0;?j?<?10;?j++)?{
System.out.println("i="+i+",j="+j);
}
}
}
}.start();*/
//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?block
e.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?block
e.printStackTrace();
}
}
for?(int?j?=?0;?j?<5;?j++)?{
System.out.println(Thread.currentThread().getName()+":i="+i+",j="+j);
}
bShouldMain=false;
ThreadTest.class.notify();
}
}
}
以上就是動力節點java培訓機構的小編針對“面試常出現的Java上機練習題及答案”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業老師隨時為你服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習