java第十次作业----多线程

java第十次作业

(一)学习总结

1.用思维导图对java多线程的学习内容进行总结。
参考资料: XMind。

2.下面是一个单线程实现的龟兔赛跑游戏。

public class TortoiseHareRace {
    public static void main(String[] args) {
        int totalStep = 10;
        int tortoiseStep = 0;
        int hareStep = 0;
        boolean[] flags = {true,false};
        System.out.println("龟兔赛跑开始了...");
        while(tortoiseStep < totalStep && hareStep < totalStep){
            tortoiseStep++;
            System.out.println("乌龟跑了"+tortoiseStep+"步...");
            boolean isHareSleep = flags[((int)(Math.random()*10))%2];
            if(isHareSleep){
                System.out.println("兔子睡着了zzzz");
            }else{
                hareStep += 2;
                System.out.println("兔子跑了"+hareStep+"步...");
            }
        }       
    }
}

阅读程序,采用实现Runnable接口的方式用多线程实现这个小游戏。下面给出主线程类,补充Tortoise线程类和Hare线程类。

public class TortoiseHareRace { 
    public static void main(String[] args) {
        Tortoise tortoise = new Tortoise(10);
        Hare hare = new Hare(10);
        Thread tortoiseThread = new Thread(tortoise);
        Thread hareThread = new Thread(hare);
        tortoiseThread.start();
        hareThread.start();
    }
}

Tortoise线程类:

class Tortoise extends Thread
{
     
	private int totalStep=10;   
     private int tortoiseStep = 0;
     public Tortoise(String name){  super(name);  }
     boolean[] flags = {true,false};
	public Tortoise(int totalStep) {
		this.totalStep=totalStep;
	}
	public int getTortoiseStep() {
		return tortoiseStep;
	}

	public void setTortoiseStep(int tortoiseStep) {
		this.tortoiseStep = tortoiseStep;
	}
	public void run(){
		 int hareStep = 0;
		while(tortoiseStep < totalStep && hareStep < totalStep){
             tortoiseStep++;
             System.out.println("乌龟跑了"+tortoiseStep+"步...");
             boolean isHareSleep = flags[((int)(Math.random()*10))%2];
             if(isHareSleep){
                 System.out.println("兔子睡着了zzzz");
             }else{
                 hareStep += 2;
                 System.out.println("兔子跑了"+hareStep+"步...");
             }
             if(tortoiseStep>0){
             try{
                     Thread.sleep(300);
             }catch(InterruptedException e){
                   e.printStackTrace();
            }
       }
 }}
	
}

Hare线程类:

class Hare extends Thread
{    
	private int hareStep = 0;
     private int totalStep=10;   
     private int tortoiseStep = 0;
     public Hare(String name){  super(name);  }
     boolean[] flags = {true,false};
	public Hare(int hareStep) {
		this.setHareStep(hareStep);
	}
	public int getHareStep() {
		return hareStep;
	}
	public void setHareStep(int hareStep) {
		this.hareStep = hareStep;
	}
	 public void run(){
		 int hareStep = 0;
		while(tortoiseStep < totalStep && hareStep < totalStep){
             tortoiseStep++;
             System.out.println("乌龟跑了"+tortoiseStep+"步...");
             boolean isHareSleep = flags[((int)(Math.random()*10))%2];
             if(isHareSleep){
                 System.out.println("兔子睡着了zzzz");
             }else{
                 hareStep += 2;
                 System.out.println("兔子跑了"+hareStep+"步...");
             }
             if(tortoiseStep>0){
             try{
                     Thread.sleep(300);
             }catch(InterruptedException e){
                   e.printStackTrace();
            }
       }
 }}
	
}

运行结果:

运行成功。
3.下面的程序是模拟了生产者——消费者问题,生产者生产10个数,消费者依次消费10个数,运行程序,看结果是否正常?存在什么问题?说明原因。使用synchronized, wait, notify解决程序出现的问题。写出修改的部分程序即可。

class Consumer implements Runnable {
    private Clerk clerk;
    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }
    public void run() {
        System.out.println("消费者开始消耗整数......");
        // 消耗10个整数
        for(int i = 1; i <= 10; i++) {
            try {
                 // 等待随机时间
                Thread.sleep((int) (Math.random() * 3000));
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }              
            clerk.getProduct();// 从店员处取走整数
        }
    }
 }
class Producer implements Runnable {
    private Clerk clerk;
    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }
    public void run() {
        System.out.println( "生产者开始生产整数......");
        // 生产1到10的整数
        for(int product = 1; product <= 10; product++) {
            try {
                Thread.sleep((int) Math.random() * 3000);
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }
           clerk.setProduct(product); // 将产品交给店员
        }
    } 
}
public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Thread consumerThread = new Thread(new Consumer(clerk)); 
        Thread producerThread = new Thread(new Producer(clerk)); 
        consumerThread.start(); 
        producerThread.start(); 
    }
}
class Clerk {
    private int product = -1; // -1 表示目前没有产品 
     // 这个方法由生产者呼叫
    public void setProduct(int product) {
        this.product = product; 
        System.out.printf("生产者设定 (%d)%n", this.product);      
    } 
    // 这个方法由消费者呼叫
    public int getProduct() {          
        int p = this.product; 
        System.out.printf("消费者取走 (%d)%n", this.product);      
        return p; 
    } 
}

运行结果:有问题。

4.其他需要总结的内容。

  1. 同步代码块:
    在代码块上加上“synchronized”关键字,则此代码块就称为同步代码块。
    同步代码块格式:
    synchronized(同步对象(this)){
    需要同步的代码 ;
    }
    2.同步方法:
    使用synchronized关键字将一个方法声明成同步方法。
    同步方法定义格式:
    synchronized 方法返回值 方法名称(参数列表){}
    3.多线程通信
    Info类:存储共享的数据信息;
    Producer类:产生Info数据的线程;
    Consumer类:使用Info数据的线程;
    class Info{ //定义信息类

    private String info;
    public void set(String info) { //产生数据
    this.info = info;
    }
    public String get() { //获取数据
    return info;
    }
    }

(二)实验总结
实验内容:
1.模拟三个老师同时分发80分作业,每个老师相当于一个线程。

1.使用implements实现继承多个接口:
定义一个实现Runnable接口的类。
定义方法run( )。Runnable接口中只有一个抽象方法run( ),实现它的类必须覆盖此方法。

private int grade=80;
     public void run(){
         while(true){
              Grade();
            if(grade <=0){     break;   }
        }          
     }

声明private int grade=80;一共有80份作业,重写run()方法,执行成功调用Grade();如果grade <=0`则跳出程序,结束。
2, 使用sleep()方法:线程休眠,让正在执行的线程进行暂时的休眠(
使用interrupt()方法中断线程
,InterruptedException方法时进行异常捕获,结束休眠。。

private  synchronized void Grade(){
         if(grade>0){
             try{
                    Thread.sleep(300);
             }catch(InterruptedException e){
                     e.printStackTrace();
             }
             System.out.println( Thread.currentThread().getName()
                +"正在发分发第" +grade--+"份作业" );   

类图结构:

2.模拟一个银行存款的程序。假设有两个储户都去银行往同一个账户进行存款,一次存100,每人存三次。要求储户每存一次钱,账户余额增加100,并在控制台输出当前账户的余额。
完成实验内容,代码上传到码云,对完成实验内容过程中遇到的问题、解决方案和思考等进行归纳总结,注意代码中必须有必要的注释。

1,设置次数每个账户time=3次,
增加一个标志位--布尔变量flag,初始化为true
在run()方法中,使用的while循环。

private int time=3;
 int sum=0;
 public void run(){
     while(true){
          Bank();
        if(time <=0){     break;   }
    }          
 }

2,每存入一次钱循环sum+100,同时次数少一次。
使用interrupt()方法中断线程,InterruptedException方法时进行异常捕获,结束休眠。。

private  synchronized void Bank(){
     if(time>0){sum=sum+100;
         try{
                Thread.sleep(300);
         }catch(InterruptedException e){
                 e.printStackTrace();
         }
         System.out.println( Thread.currentThread().getName()
            +"还有   " +--time+"  次存钱机会---现该账户中存款数额共计   :  "+sum+"元");   
    }

类图结构:

(三)代码托管(务必链接到你的项目)
码云commit历史截图
上传实验项目代码到码云,在码云项目中选择“统计-commits”,设置搜索时间段,搜索本周提交历史,并截图。

https://git.oschina.net/hebau_cs15/java-cs02zt06.git

https://git.oschina.net/hebau_cs15/java-cs02zt06.git

原文地址:https://www.cnblogs.com/zhaotong189800/p/6921721.html