資源簡介
自己學(xué)著編寫的一個JAVA多線程程序,該程序?qū)崿F(xiàn)的功能是:在主線程main中創(chuàng)建兩個子線程,A和B,線程A先運行,再運行B線程,當兩個子線程都運行完畢后,才運行主線程,并最終結(jié)束整個程序的運行。
希望該程序?qū)Τ鯇W(xué)JAVA線程的朋友有幫助...
希望該程序?qū)Τ鯇W(xué)JAVA線程的朋友有幫助...
代碼片段和文件信息
package?thread;
/**
?*?write?by?agan?
?*?E-mail:gsqsunny@gmain.com
?*?2009.1.3
?*?通過實現(xiàn)?Runnable?接口實現(xiàn)多線程
?*?description:
?*?????????????We?create?two?subThreads?(thread?A?and?thread?B?)in?the?main?thread.
?*?????????????The?main?thread?is?started?firstly?then?the?thread?A?is?started.?
?*?????????????When?the?thread?A?run?over?the?thread?B?is?started.
?*?????????????The?main?thread?run?over?until?the?two?subThreads?are?over?.
?*/
public?class?TestMitiThreadrunable?implements?Runnable{
/**
?*?@param?args
?*/
public?static?void?main(String[]?args)?{
//?TODO?Auto-generated?method?stub
System.out.println(Thread.currentThread().getName()?+?“?線程運行開始!“);
System.out.println(“----------------------------------------“);
TestMitiThreadrunable?test?=?new?TestMitiThreadrunable();
????????Thread?thread1?=?new?Thread(test);
????????Thread?thread2?=?new?Thread(test);
????????thread1.setName(“A“);
????????thread1.start();
????????thread2.setName(“B“);
????????//?wait?for?thread1?is?over?then?startup?thread2
????????try?{
thread1.join();
}?catch?(InterruptedException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
????????thread2.start();
????????if(thread2.isAlive())
try?{
Thread.currentThread().sleep(1000);
}?catch?(InterruptedException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
System.out.println(“----------------------------------------“);
????????System.out.println(Thread.currentThread().getName()?+?“?線程運行結(jié)束!“);
}
public?void?run(){
System.out.println(“----------------------------------------“);
System.out.println(Thread.currentThread().getName()+“?線程運行開始!“);
System.out.println(“ThreadName????:“+Thread.currentThread().getName());
System.out.println(“ThreadID??????:“+Thread.currentThread().getId());
System.out.println(“ThreadPriority:“+Thread.currentThread().getPriority());
System.out.println(“ThreadGroup???:“+Thread.currentThread().getThreadGroup());
for?(int?i?=?0;?i?10;?i++)?{
System.out.println(i?+?“?“?+?Thread.currentThread().getName());
try?{
Thread.sleep((int)?Math.random()?*?10);
}?catch?(InterruptedException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()?+?“?線程運行結(jié)束!“);
System.out.println(“----------------------------------------“);
}
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件???????2475??2009-01-03?14:30??java?多線程實例\TestMitiThreadrunable.java
?????文件????????684??2009-01-03?14:30??java?多線程實例\運行結(jié)果.txt
?????目錄??????????0??2009-01-03?14:31??java?多線程實例
-----------?---------??----------?-----??----
?????????????????3159????????????????????3
- 上一篇:JAVA計算器實驗報告與源碼
- 下一篇:java多人五子棋源碼
評論
共有 條評論