資源簡(jiǎn)介
實(shí)驗(yàn)七 Java多線程
一、實(shí)驗(yàn)?zāi)康模?熟悉利用Thread類建立多線程方法。
熟悉利用Thread接口建立多線程方法。
二、實(shí)驗(yàn)內(nèi)容:
1. 閱讀下列程序,分析并上機(jī)檢驗(yàn)其功能。
class DelayThread exends Thread{
private static int count=0;
private int no;
private int delay;
public DelayThread(){
count++;
no=count;
}
public void run(){
try{
for (int i=0;i<10;i++){
delay=(int)(Math.random()*5000);
sleep(delay);
System.out.println(“Thread ”+no+” with a delay ”+delay);
}
}catch(InterruptedException e){}}}
public class MyThread{
public static void main(String args[]){
DelayThread thread1=new DelayThread();
DelayThread thread2=new DelayThread();
thread1.start();
thread2.start();
try{ Thread.sleep(1000);}catch(InterruptedException e){
System.out.println(“Thread wrong”);}}}
2.講上列程序利用Runnable接口改寫,并上機(jī)檢驗(yàn)。
3.利用多線程編寫一個(gè)模擬時(shí)鐘(AWT程序、Runnable接口),有時(shí)/分/秒針
編寫一個(gè)應(yīng)用程序,創(chuàng)建三個(gè)線程分別顯示各自的時(shí)間。
三、實(shí)驗(yàn)要求:
1. 通過(guò)實(shí)驗(yàn)掌握Thread 、Runnable使用方法;
2. 程序必須能夠?qū)崿F(xiàn)多線程;
3. 程序必須能夠完成題目要求;
4. 寫出實(shí)驗(yàn)報(bào)告。
四、實(shí)驗(yàn)步驟:
首先分析程序功能,再通過(guò)上機(jī)運(yùn)行驗(yàn)證自己的分析,從而掌握通過(guò)Thread類建立多線程的方法。
通過(guò)將擴(kuò)展Thread類建立多線程的方法改為利用Runnable接口的方法,掌握通過(guò)Runnable接口建立多線程的方法。

代碼片段和文件信息
package?模擬時(shí)鐘;
/*作者:王玲
時(shí)間:2016-6-10*/
import?java.util.Calendar;//自動(dòng)導(dǎo)包?ctrl+shfit+o
public?class?Clock?implements?Runnable{//使用接口實(shí)現(xiàn)
@Override
public?synchronized?void?run()?{//線程同步,run方法
//?TODO?Auto-generated?method?stub
Calendar?calendar=Calendar.getInstance();//使用時(shí)間Calendar類
try?{
Thread.sleep(1000);//線程休眠一秒,使結(jié)果看的更加清晰
System.out.println(“現(xiàn)在是“+(calendar.get(Calendar.HOUR_OF_DAY)+“時(shí)“));//顯示小時(shí)
System.out.println(“現(xiàn)在是“+(calendar.get(Calendar.MINUTE)+“分“));//顯示分鐘
System.out.println(“現(xiàn)在是“+(calendar.get(Calendar.SECOND)+“秒“));//顯示秒
}?catch?(InterruptedException?e)?{
//?TODO?Auto-generated?catch?block
System.out.println(“Thread?wrong“);
e.printStackTrace();//打印異常
}
}
public?static?void?main(String[]?args)?{
Clock?clock=new?Clock();//實(shí)例化對(duì)象
Thread?a=new?Thread(clock“時(shí)“);//創(chuàng)建線程,修改線程名
Thread?b=new?Thread(clock“分“);
Thread?c=new?Thread(clock“秒“);
a.start();//啟動(dòng)線程
b.start();
c.start();
}
}
?屬性????????????大小?????日期????時(shí)間???名稱
-----------?---------??----------?-----??----
?????目錄???????????0??2016-06-10?16:14??實(shí)驗(yàn)七代碼\
?????文件????????1083??2016-06-10?15:59??實(shí)驗(yàn)七代碼\Clock.java
?????文件????????1064??2016-06-10?15:38??實(shí)驗(yàn)七代碼\DelayThread.java
評(píng)論
共有 條評(píng)論