实验八 Java多线程操作
(实验报告)
一、目的
1.掌握Java多线程操作。
二、实验内容
启动线程,线程休眠,线程同步,等待和唤醒
三、实验环境
JDK1.6+dos环境
四、实验原理
通过案例掌握多线程操作。
五、实验步骤
1、设计一个线程操作类,要求可以产生三个线程对象,并可以分
别设置三个线程的休眠时间,如下所示:
线程A,休眠10秒
线程B,休眠20秒
线程C,休眠30秒
2、生产者与消费者问题,生产者生产一台电脑,消费者马上将生
产出的电脑取走。
六、实验小结
1、class MyThread implements Runnable{
String name;
int time;
public MyThread(String name,int time){
=name;
this.time=time;
}
public void run(){
try{
Thread.sleep(this.time);
}
catch(Exception e){
}
System.out.println(+"线程,休眠"+this.time/1000+"秒");
}
}
public class Demo08{
public static void main(String args[]){
MyThread mt1=new MyThread("线程A",10000);
MyThread mt2=new MyThread("线程B",20000);
MyThread mt3=new MyThread("线程C",30000);
new Thread(mt1).start();
new Thread(mt2).start();
new Thread(mt3).start();
}
}
//生产电脑和搬运电脑
class Computer{
private String name;
public static int sum=0;
private boolean flag=true;
public Computer(String name){
=name;
}
public synchronized void set(){ //生产电脑if(!flag){
try{
super.wait();
}
catch(Exception e){
e.printStackTrace();
}
}
sum=sum+1;
System.out.println("第"+sum+"台"+name+"电脑被生产");
flag=false;
super.notify();
}
public synchronized void get(){ //搬走电脑
if(flag){
try{
super.wait();
}
catch(Exception e){
e.printStackTrace();
}
}
System.out.println("第"+sum+"台"+name+"电脑被搬走");
flag=true;
super.notify();
}
}
class Producter implements Runnable{ private Computer c=null;
public Producter(Computer c){
this.c=c;
}
public void run(){
for(int i=0;i<1000;i++){
this.c.set();
}
}
}
class Worker implements Runnable{ private Computer c=null;
public Worker(Computer c){
this.c=c;
}
public void run(){
for(int i=0;i<1000;i++){
this.c.get();
}
}
}
public class Test{
public static void main(String args[]){ Computer c=new Computer("联想");
Producter p=new Producter(c);
Worker w=new Worker(c);
new Thread(p).start();
new Thread(w).start();
}
}。