实验12 java多线程含答案.docx
- 文档编号:10596131
- 上传时间:2023-02-21
- 格式:DOCX
- 页数:21
- 大小:22.64KB
实验12 java多线程含答案.docx
《实验12 java多线程含答案.docx》由会员分享,可在线阅读,更多相关《实验12 java多线程含答案.docx(21页珍藏版)》请在冰豆网上搜索。
实验12java多线程含答案
实验12:
Java多线程
一、实验目的
(1)了解线程的概念。
(2)学习简单的多线程编程。
二、实验任务
(1)阅读给定的JavaApplication程序,按要求回答问题并写出运行结果。
(2)按要求编写一个JavaApplication程序,并编译、运行这个程序。
三、实验内容
1.输入下面的JavaApplication程序,运行该程序,并简要分析程序的运行结果。
1:
classSimpleThreadextendsThread{
2:
publicSimpleThread(Stringstr){
3:
【代码1】super(str);//调用其父类的构造方法
4:
}
5:
publicvoidrun(){//重写run方法
6:
for(inti=0;i<10;i++){
7:
System.out.println(i+""+getName());
8:
//打印次数和线程的名字
9:
try{
10:
sleep((int)(Math.random()*1000));
11:
//线程睡眠,把控制权交出去
12:
}
13:
catch(【代码2】){}//捕获中断异常
14:
}
15:
System.out.println("DONE!
"+getName());
16:
//线程执行结束
17:
}
18:
}
1:
publicclassTwoThreadsTest{
2:
publicstaticvoidmain(Stringargs[]){
3:
newSimpleThread("First").start();
4:
//第一个线程的名字为First
5:
SimpleThreadspt=newSimpleThread("Second");//第二个线程的名字为Second
6:
【代码3】spt.start();//启动second线程
7:
}
8:
}
2、使用接口创建线程
1:
publicclassMyThread2implementsRunnable【代码1】{
2:
intcount=1,number;
3:
publicMyThread2(inti){
4:
number=i;
5:
System.out.println("创建线程"+number);
6:
}
7:
publicvoidrun()【代码2】{//重写run()方法
8:
while(true){
9:
System.out.println("线程"+number+":
计数"+count);
10:
if(++count==6)return;
11:
}
12:
}
13:
publicstaticvoidmain(String[]args){
14:
for(inti=0;i<5;i++)
15:
newThread(【代码3】).start();
16:
}}
3、实现两个定时线程,一个线程每隔1秒显示一次,一个线程每隔3秒显示一次。
答:
源程序:
importjava.io.*;
publicclassTime
{
staticLefthandleft; //声明静态的类的对象
staticRighthandright;
public staticvoidmain(Stringargs[])
{
left=newLefthand() ; //创建两个线程。
right=newRighthand();
left.start();//线程开始运行后,Lefthand类中的run方法将被执行。
right.start();
}
}
classLefthandextendsThread //lefthand类继承Thread类
{
publicvoidrun()
{
for(;;)
{
System.out.println("每1秒显示一次!
");
Try
{
sleep(1000); //使当前活动线程睡眠1秒
}
catch(InterruptedExceptione){} //捕捉异常
}
}
}
classRighthandextendsThread
{
publicvoidrun()
{
for(;;)
{
System.out.println("每3秒显示一次!
");
Try
{
sleep(3000);
}
catch(InterruptedExceptione){}
}
}
}
运行结果:
(这一列是注释)
每1秒显示一次
每3秒显示一次
每1秒显示一次
每1秒显示一次
每3秒显示一次
每1秒显示一次
每1秒显示一次
每1秒显示一次
每3秒显示一次
每1秒显示一次
每1秒显示一次
每1秒显示一次
每3秒显示一次
每1秒显示一次
每1秒显示一次
每1秒显示一次
每3秒显示一次
每1秒显示一次
每1秒显示一次
3、创建两个线程,每个线程打印出线程名字后再睡眠,给其它线程以执行的机会,主线程也要打印出线程名字后再睡眠,每个线程前后共睡眠5次。
要求分别采用从Thread中继承和实现Runnable接口两种方式来实现程序。
(即写两个程序)
importjava.io.*;
classNameThreadextendsThread{
inttime;//睡眠的时间
publicNameThread(Stringn,intt){
super(n);
time=t;
}
publicvoidrun(){
for(inti=1;i<=5;i++){
System.out.println(getName()+""+i);
try{
Thread.sleep(time);
}catch(InterruptedExceptione){return;}
}
}
publicstaticvoidmain(Stringargs[]){
NameThreadbonnie=newNameThread("Bonnie",1000);
bonnie.start();
NameThreadclyde=newNameThread("Clyde",700);
clyde.start();
for(inti=1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+""+i);
try{
Thread.sleep(1100);
}catch(InterruptedExceptione){return;}
}
}
}
实验六多线程
【目的】
掌握使用Thread的子类创建线程;
学习使用Thread类创建线程;
学习处理线程同步问题。
【内容】
1.汉字打字练习。
✧实验要求:
编写一个Java应用程序,在主线程中再创建一个Frame类型的窗口,在该窗口中再创建1个线程giveWord。
线程giveWord每隔2秒钟给出一个汉字,用户使用一种汉字输入法将该汉字输入到文本框中。
✧程序运行效果示例:
程序运行效果如下图所示:
✧程序模板:
WordThread.java
importjava.awt.*;
publicclassWordThreadextendsThread
{charword;
intk=19968;
Labelcom;
WordThread(Labelcom)
{=com;
}
publicvoidrun()
{k=19968;
while(true)
{
word=(char)k;
com.setText(""+word);
try{【代码1】//调用sleep方法使得线程中断6000豪秒
}
catch(InterruptedExceptione){}
k++;
if(k>=29968)k=19968;
}
}
}
ThreadFrame.java
importjava.awt.*;
importjava.awt.event.*;
publicclassThreadFrameextendsFrameimplementsActionListener
{
LabelwordLabel;
Buttonbutton;
TextFieldinputText,scoreText;
【代码2】//用WordThread声明一个giveWord对象
intscore=0;
ThreadFrame()
{wordLabel=newLabel("",Label.CENTER);
wordLabel.setFont(newFont("",Font.BOLD,72));
button=newButton("开始");
inputText=newTextField(3);
scoreText=newTextField(5);
scoreText.setEditable(false);
【代码3】//创建giveWord,将wordLabel传递给WordThread构造方法的参数
button.addActionListener(this);
inputText.addActionListener(this);
add(button,BorderLayout.NORTH);
add(wordLabel,BorderLayout.CENTER);
PanelsouthP=newPanel();
southP.add(newLabel("输入标签所显示的汉字后回车:
"));
southP.add(inputText);
southP.add(scoreText);
add(southP,BorderLayout.SOUTH);
setBounds(100,100,350,180);
setVisible(true);
validate();
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
}
);
}
publicvoidactionPerformed(ActionEvente)
{
if(e.getSource()==button)
{if(!
(【代码4】))//giveWord调用方法isAlive()
{giveWord=newWordThread(wordLabel);
}
try
{【代码5】//giveWord调用方法start()
}
catch(Exceptionexe){}
}
elseif(e.getSource()==inputText)
{if(inputText.getText().equals(wordLabel.getText()))
{score++;
}
scoreText.setText("得分:
"+score);
inputText.setText(null);
}
}
}
WordThread.java
publicclassThreadWordMainClass
{publicstaticvoidmain(Stringargs[])
{newThreadFrame();
}
✧实验后的练习:
1.在WordThread类中增加int型的成员time,其初值为6000,将其中的【代码1】更改为线程中断time毫秒。
在WordThread类增加publicvoidsetTime(intn)方法,使得WordThread线程对象可以调用该方法修改time的值。
2.旋转的行星。
✧实验要求:
编写一个应用程序,模拟月亮围绕地球旋转、地球围绕太阳旋转。
✧程序运行效果示例:
程序运行效果如下图所示:
✧程序模板:
Mycanvas.java
importjava.awt.*;
publicclassMycanvasextendsCanvas
{intr;
Colorc;
publicvoidsetColor(Colorc)
{this.c=c;
}
publicvoidsetR(intr)
{this.r=r;
}
publicvoidpaint(Graphicsg)
{g.setColor(c);
g.fillOval(0,0,2*r,2*r);
}
publicintgetR()
{returnr;
}
}
Planet.java
importjava.awt.*;
publicclassPlanetextendsPanelimplementsRunnable
{【代码1】//用Thread类声明一个moon对象
MycanvasyellowBall;
doublepointX[]=newdouble[360],
pointY[]=newdouble[360];//用来表示画布左上角端点坐标的数组
intw=100,h=100;
intradius=30;
Planet()
{setSize(w,h);
setLayout(null);
yellowBall=newMycanvas();
yellowBall.setColor(Color.yellow);
add(yellowBall);
yellowBall.setSize(12,12);
yellowBall.setR(12/2);
pointX[0]=0;
pointY[0]=-radius;
doubleangle=1*Math.PI/180;//刻度为1度
for(inti=0;i<359;i++)//计算出数组中各个元素的值
{pointX[i+1]=pointX[i]*Math.cos(angle)-Math.sin(angle)*pointY[i];
pointY[i+1]=pointY[i]*Math.cos(angle)+pointX[i]*Math.sin(angle);
}
for(inti=0;i<360;i++)
{pointX[i]=pointX[i]+w/2;//坐标平移
pointY[i]=pointY[i]+h/2;
}
yellowBall.setLocation((int)pointX[0]-yellowBall.getR(),
(int)pointY[0]-yellowBall.getR());
【代码2】//创建moon线程,当前面板做为该线程的目标对象
}
publicvoidstart()
{try{moon.start();
}
catch(Exceptionexe){}
}
publicvoidpaint(Graphicsg)
{g.setColor(Color.blue);
g.fillOval(w/2-9,h/2-9,18,18);
}
publicvoidrun()
{inti=0;
while(true)
{i=(i+1)%360;
yellowBall.setLocation((int)pointX[i]-yellowBall.getR(),
(int)pointY[i]-yellowBall.getR());
try{【代码3】//Thread类调用类方法sleep使得线程中断10豪秒
}
catch(InterruptedExceptione){}
}
}
}
HaveThreadFrame.java
importjava.awt.*;
importjava.awt.event.*;
publicclassHaveThreadFrameextendsFrameimplementsRunnable
{【代码4】//用Thread类声明一个rotate对象
Planetearth;
doublepointX[]=newdouble[360],
pointY[]=newdouble[360];
intwidth,height;
intradius=120;
HaveThreadFrame()
{rotate=newThread(this);
earth=newPlanet();
setBounds(0,0,360,400);
width=getBounds().width;
height=getBounds().height;
pointX[0]=0;
pointY[0]=-radius;
doubleangle=1*Math.PI/180;
for(inti=0;i<359;i++)
{pointX[i+1]=pointX[i]*Math.cos(angle)-Math.sin(angle)*pointY[i];
pointY[i+1]=pointY[i]*Math.cos(angle)+pointX[i]*Math.sin(angle);
}
for(inti=0;i<360;i++)
{pointX[i]=pointX[i]+width/2;
pointY[i]=pointY[i]+height/2;
}
setLayout(null);
setVisible(true);
validate();
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
}
);
add(earth);
earth.setLocation((int)pointX[0]-earth.getSize().width/2,
(int)pointY[0]-earth.getSize().height/2);
earth.start();
【代码5】//用rotate调用start方法
}
publicvoidrun()
{inti=0;
while(true)
{i=(i+1)%360;
earth.setLocation((int)pointX[i]-earth.getSize().width/2,
(int)pointY[i]-earth.getSize().height/2);
try{Thread.sleep(100);
}
catch(InterruptedExceptione){}
}
}
publicvoidpaint(Graphicsg)
{g.setColor(Color.red);
g.fillOval(width/2-15,height/2-15,30,30);
}
}
HaveThreadFrame.java
publicclassThreadRotateMainClass
{publicstaticvoidmain(Stringargs[])
{newHaveThreadFrame();
}
}
✧实验后的练习:
1.在Planet类中再增加一个Mycanvas对象greenBall和一个Thread对象Satellite,线程Satellite占有CPU资源期间可以让greenBall画布旋转。
3.双线程接力。
✧实验要求:
编写一个应用程序,除了主线程外,还有两个线程:
first和second。
first负责模拟一个红色的按钮从坐标(10,60)运动到(100,60);second负责模拟一个绿色的按钮从坐标(100,60)运动到(200,60)。
✧程序运行效果示例:
程序运行效果如下图所示:
✧程序模板:
MoveButton.java
importjava.awt.*;
importjava.awt.event.*;
publicclassMoveButtonextendsFrameimplementsRunnable,ActionListener
{【代码1】//用Thread类声明first,second两个线程对象
ButtonredButton,greenButton,startButton;
intdistance=10;
MoveButton()
{【代码2】//创建first线程,当前窗口做为该线程的目标对象
【代码3】//创建first线程,当前窗口做为该线程的目标对象
redButton=newButton();
greenButton=newButton();
redButton.setBackground(Color.red);
greenButton.setBackground(Color.green);
startButton=newButton("start");
startButton.addActionListener(this);
setLayout(null);
add(redButton);
redButton.setBounds(10,60,15,15);
add(greenButton);
greenButton.setBounds(100,60,15,15);
add(startButton);
startButton.setBounds(10,100,30,30);
setBounds(0,
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 实验12 java多线程含答案 实验 12 java 多线程 答案