zoukankan      html  css  js  c++  java
  • Java第十次作业--多线程

    Java第十次作业--多线程


    (一)学习总结

    1,用思维导图对java多线程的学习内容进行总结。


    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线程类。

    补充后的程序为:

    package workp;
    
    
    class Tortoise implements Runnable {
    	private int tortoiseStep = 0;
    	private int totalStep = 10;
    
    	public Tortoise(int tortoiseStep) {
    		this.tortoiseStep = tortoiseStep;
    	}
    
    	public void run() {
    		while (tortoiseStep < totalStep) {
    			tortoiseStep++;
    			System.out.println("乌龟跑了" + tortoiseStep + "步");
    		}
    	}
    }
    
    class Hare implements Runnable {
    	private int step = 0;
    	private int totalStep = 10;
    	boolean[] flags = { true, false };
    
    	public Hare(int step) {
    		this.step = step;
    	}
    
    	public void run() {
    		while (step < this.totalStep) {
    			boolean isHareSleep = flags[((int) (Math.random() * 10)) % 2];
    			if (isHareSleep) {
    				System.out.println("兔子睡着了!");
    			} else {
    				this.step=this.step+2;
    				System.out.println("兔子跑了" + this.step + "步");
    			}
    		}
    	}
    }
    
    public class Test {
    	public static void main(String[] args) {
    		Tortoise tortoise = new Tortoise(0);
    		Hare hare = new Hare(0);
    		System.out.println("龟兔赛跑开始了...");
    		Thread tortoiseThread = new Thread(tortoise);
    		Thread hareThread = new Thread(hare);
    		tortoiseThread.start();
    		hareThread.start();
    	}
    }
    

    程序截图如下:


    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; 
        } 
    }
    

    修改后的代码:

    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();
                }
            }
       }
    }
    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); // 将产品交给店员
            }
            }
         }
    class Clerk {
        private int product = -1; // -1 表示目前没有产品
        private int p ;
     // 这个方法由生产者呼叫
     public synchronized void setProduct(int product) {
        if (this.product != -1) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.product = product;
        p = this.product;
        System.out.printf("生产者设定 (%d)%n", this.product);
        getProduct();
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.product = -1;
        super.notify();
    }
        // 这个方法由消费者呼叫
        public synchronized int getProduct() {
            if (this.product == -1) {
                try {
                    super.wait();
                }catch (InterruptedException e) {
            e.printStackTrace();
                }
            }
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("消费者取走 (%d)%n", p);
        this.product = -1;
        super.notify();
        return this.product;
    }
    }
    public class Test {
        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(); 
        }
    }
    


    (二)实验总结

    实验内容:
    1.模拟三个老师同时分发80分作业,每个老师相当于一个线程。
    程序代码:

    package work;
    class Page implements Runnable{
    	private int page=80;
    	public void run(){
    		for(int i=1;i<81;i++){
    			if(page>0){
    				System.out.println(Thread.currentThread().getName()+"正在分发第"+page--+"张试卷");
    			}else{
    				System.exit(1);
    			}
    		}
    	}
    }
    public class Work {
    	public static void main(String args[]){
    		Page p=new Page();
    		new Thread(p,"1").start();
    		new Thread(p,"2").start();
    		new Thread(p,"3").start();
    	}
    }
    

    程序截图:


    2.模拟一个银行存款的程序。假设有两个储户都去银行往同一个账户进行存款,一次存100,每人存三次。要求储户每存一次钱,账户余额增加100,并在控制台输出当前账户的余额。

    问题:最后存款金额不对

    解决:没有对Bank类进行同步操作,导致金额不对。

    部分代码如下:

    package cunKuang;
    
    public class SavePer implements Runnable {
    	private String name;
    	private Bank b=new Bank();
    	public SavePer(){
    		
    	}
    	public SavePer(String name){
    		this.name=name;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public Bank getB() {
    		return b;
    	}
    	public void setB(Bank b) {
    		this.b = b;
    	}
    	public void run(){
    		synchronized(b){
    			for(int i=1;i<4;i++){
    				try {
    					Thread.sleep(300);
    					b.save();
    				} catch (InterruptedException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    				System.out.println(Thread.currentThread().getName()+"第"+i+"次存款,"+name+"的余额为:"+b.getYue());
    			}
    		}
    	}
    }
    

    程序运行截图如下:


    (三)代码托管

    博客网站 https://yamon.top 个人网站 https://yamon.top/resume GitHub网站 https://github.com/yamonc 欢迎前来访问
  • 相关阅读:
    SQLServer数据库中开启CDC导致“事务日志空间被占满,原因为REPLICATION”的原因分析和解决办法
    译:SQL Server的Missing index DMV的 bug可能会使你失去理智---慎重看待缺失索引DMV中的信息
    SQLServer中间接实现函数索引或者Hash索引
    MySQL缓存分类和配置
    MySQL系统变量配置基础
    MySQL索引统计信息更新相关的参数
    Sql Server优化---统计信息维护策略
    SQL Server 用角色(Role)管理数据库权限
    sp_executesql 或者 EXECUTE 执行动态sql的权限问题
    关于T-SQL重编译那点事,内联函数和表值函数在编译生成执行计划的区别
  • 原文地址:https://www.cnblogs.com/chenyameng/p/6928678.html
Copyright © 2011-2022 走看看