201772020113 李清华《面向对象程序设计(java)》第17周学习总结

1、实验目的与要求

(1) 掌握线程同步的概念及实现技术;

(2) 线程综合编程练习

2、实验内容和步骤

实验1:测试程序并进行代码注释。

测试程序1:

l  在Elipse环境下调试教材651页程序14-7,结合程序运行结果理解程序;

l  掌握利用锁对象和条件对象实现的多线程同步技术。

 1 package synch;
 2
 3 import java.util.*;
 4 import java.util.concurrent.locks.*;
 5
 6 /**
 7  * A bank with a number of bank accounts that uses locks for serializing access.
 8  * @version 1.30 2004-08-01
 9  * @author Cay Horstmann
10  */
11 public class Bank
12 {
13    private final double[] accounts;//银行的基本数据
14    private Lock bankLock;//锁对象
15    private Condition sufficientFunds;
16
17    /**
18     * Constructs the bank.
19     * @param n the number of accounts
20     * @param initialBalance the initial balance for each account
21     */
22    public Bank(int n, double initialBalance)
23    {
24       accounts = new double[n];
25       Arrays.fill(accounts, initialBalance);
26       bankLock = new ReentrantLock();
27       sufficientFunds = bankLock.newCondition();
28    }
29
30    /**
31     * Transfers money from one account to another.
32     * @param from the account to transfer from
33     * @param to the account to transfer to
34     * @param amount the amount to transfer
35     */
36    public void transfer(int from, int to, double amount) throws InterruptedException
37    {
38       bankLock.lock();
39       try
40       {  //锁对象的引用条件对象
41          while (accounts[from] < amount)
42             sufficientFunds.await();
43          System.out.print(Thread.currentThread());//打印出线程号
44          accounts[from] -= amount;
45          System.out.printf(" %10.2f from %d to %d", amount, from, to);
46          accounts[to] += amount;
47          System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
48          sufficientFunds.signalAll();
49       }
50       finally
51       {
52          bankLock.unlock();
53       }
54    }
55
56    /**
57     * Gets the sum of all account balances.
58     * @return the total balance
59     */
60    public double getTotalBalance()
61    {
62       bankLock.lock();//加锁
63       try
64       {
65          double sum = 0;
66
67          for (double a : accounts)
68             sum += a;
69
70          return sum;
71       }
72       finally
73       {
74          bankLock.unlock();//解锁
75       }
76    }
77
78    /**
79     * Gets the number of accounts in the bank.
80     * @return the number of accounts
81     */
82    public int size()
83    {
84       return accounts.length;
85    }
86 }

 1 package synch;
 2
 3 /**
 4  * This program shows how multiple threads can safely access a data structure.
 5  * @version 1.31 2015-06-21
 6  * @author Cay Horstmann
 7  */
 8 public class SynchBankTest
 9 {
10    public static final int NACCOUNTS = 100;
11    public static final double INITIAL_BALANCE = 1000;
12    public static final double MAX_AMOUNT = 1000;
13    public static final int DELAY = 10;
14
15    public static void main(String[] args)
16    {
17       Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
18       for (int i = 0; i < NACCOUNTS; i++)
19       {
20          int fromAccount = i;
21          Runnable r = () -> {
22             try
23             {
24                while (true)
25                {
26                   int toAccount = (int) (bank.size() * Math.random());
27                   double amount = MAX_AMOUNT * Math.random();
28                   bank.transfer(fromAccount, toAccount, amount);
29                   Thread.sleep((int) (DELAY * Math.random()));
30                }
31             }
32             catch (InterruptedException e)
33             {
34             }
35          };
36          Thread t = new Thread(r);
37          t.start();
38       }
39    }
40 }

测试程序2:

l  在Elipse环境下调试教材655页程序14-8,结合程序运行结果理解程序;

l  掌握synchronized在多线程同步中的应用。

 1 package synch2;
 2
 3 /**
 4  * 这个程序显示了多个线程如何安全地访问数据结构,使用同步方法。
 5  * @version 1.31 2015-06-21
 6  * @author Cay Horstmann
 7  */
 8 public class SynchBankTest2
 9 {
10    public static final int NACCOUNTS = 100;
11    public static final double INITIAL_BALANCE = 1000;
12    public static final double MAX_AMOUNT = 1000;
13    public static final int DELAY = 10;
14
15    public static void main(String[] args)
16    {
17       Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
18       for (int i = 0; i < NACCOUNTS; i++)
19       {
20          int fromAccount = i;
21          Runnable r = () -> {
22             try
23             {
24                while (true)
25                {
26                   int toAccount = (int) (bank.size() * Math.random());
27                   double amount = MAX_AMOUNT * Math.random();
28                   bank.transfer(fromAccount, toAccount, amount);
29                   Thread.sleep((int) (DELAY * Math.random()));
30                }
31             }
32             catch (InterruptedException e)
33             {
34             }
35          };
36          Thread t = new Thread(r);
37          t.start();
38       }
39    }
40 }

 1 package synch2;
 2
 3 import java.util.*;
 4
 5 /**
 6  * 具有多个使用同步原语的银行账户的银行。
 7  * @version 1.30 2004-08-01
 8  * @author Cay Horstmann
 9  */
10 public class Bank
11 {
12    private final double[] accounts;
13
14    /**
15     * 建设银行。
16     * @param n the number of accounts
17     * @param initialBalance the initial balance for each account
18     */
19    public Bank(int n, double initialBalance)
20    {
21       accounts = new double[n];
22       Arrays.fill(accounts, initialBalance);
23    }
24
25    /**
26     * 把钱从一个账户转到另一个账户。
27     * @param from the account to transfer from
28     * @param to the account to transfer to
29     * @param amount the amount to transfer
30     */
31    public synchronized void transfer(int from, int to, double amount) throws InterruptedException
32    {
33       while (accounts[from] < amount)
34          wait();//导致线程进入等待状态直到它被通知。该方法只能在一个同步方法中调用。
35       System.out.print(Thread.currentThread());//打印出线程号
36       accounts[from] -= amount;
37       System.out.printf(" %10.2f from %d to %d", amount, from, to);//第一个打印结果保留两位小数(最大范围是十位)
38       accounts[to] += amount;
39       System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
40       notifyAll();//解除那些在该对象上调用wait方法的线程阻塞状态。该方法只能在同步方法或同步块内部调用。
41    }
42
43    /**
44     * 获取所有帐户余额的总和。
45     * @return the total balance
46     */
47    public synchronized double getTotalBalance()
48    {
49       double sum = 0;
50
51       for (double a : accounts)
52          sum += a;
53
54       return sum;
55    }
56
57    /**
58     * 获取银行中的帐户数量。
59     * @return the number of accounts
60     */
61    public int size()
62    {
63       return accounts.length;
64    }
65 }

测试程序3:

l  在Elipse环境下运行以下程序,结合程序运行结果分析程序存在问题;

l  尝试解决程序中存在问题。


class Cbank

{

     private static int s=2000;

     public   static void sub(int m)

     {

           int temp=s;

           temp=temp-m;

          try {

                     Thread.sleep((int)(1000*Math.random()));

                   }

           catch (InterruptedException e)  {              }

          s=temp;

          System.out.println("s="+s);

             }

}

 

 

class Customer extends Thread

{

  public void run()

  {

   for( int i=1; i<=4; i++)

     Cbank.sub(100);

    }

 }

public class Thread3

{

 public static void main(String args[])

  {

   Customer customer1 = new Customer();

   Customer customer2 = new Customer();

   customer1.start();

   customer2.start();

  }

}

改进后:

 1 class Cbank {
 2     private static int s = 2000;
 3
 4     public synchronized static void sub(int m) {
 5         int temp = s;
 6         temp = temp - m;
 7         try {
 8             Thread.sleep((int) (1000 * Math.random()));
 9         } catch (InterruptedException e) {
10         }
11         s = temp;
12         System.out.println("s=" + s);
13     }
14 }
15
16 class Customer extends Thread {
17     public void run() {
18         for (int i = 1; i <= 4; i++)
19             Cbank.sub(100);
20     }
21 }
22
23 public class Thread3 {
24     public static void main(String args[]) {
25         Customer customer1 = new Customer();
26         Customer customer2 = new Customer();
27         customer1.start();
28         customer2.start();
29     }
30 }

实验2 编程练习

利用多线程及同步方法,编写一个程序模拟火车票售票系统,共3个窗口,卖10张票,程序输出结果类似(程序输出不唯一,可以是其他类似结果)。

Thread-0窗口售:第1张票

Thread-0窗口售:第2张票

Thread-1窗口售:第3张票

Thread-2窗口售:第4张票

Thread-2窗口售:第5张票

Thread-1窗口售:第6张票

Thread-0窗口售:第7张票

Thread-2窗口售:第8张票

Thread-1窗口售:第9张票

Thread-0窗口售:第10张票

 1 public class Main {
 2     public static void main(String[] args) {
 3         Mythread mythread=new Mythread();
 4         Thread t1=new Thread(mythread);
 5         Thread t2=new Thread(mythread);
 6         Thread t3=new Thread(mythread);
 7         t1.start();
 8         t2.start();
 9         t3.start();
10     }
11 }
12 class Mythread implements Runnable{
13     int t=1;
14     boolean flag=true;
15     public void run() {
16         while(flag) {
17             try {
18                 Thread.sleep(300);
19             }catch(InterruptedException e) {
20                 e.printStackTrace();
21             }
22             synchronized(this){
23                 if(t<=10) {
24                     System.out.println(Thread.currentThread().getName() + "窗口售:第" + t + "张票");
25                     t++;
26                 }
27                 if(t>10) {
28                     flag=false;
29                 }
30             }
31         }
32     }
33 }

实验总结:本周实验学会了如何使用线程同步机制来解决多线程并发导致的不确定性。

原文地址:https://www.cnblogs.com/bmwb/p/10161625.html

时间: 2024-07-30 18:33:00

201772020113 李清华《面向对象程序设计(java)》第17周学习总结的相关文章

201771010123汪慧和《面向对象程序设计Java》第二周学习总结

一.理论知识部分 1.标识符由字母.下划线.美元符号和数字组成, 且第一个符号不能为数字.标识符可用作: 类名.变量名.方法名.数组名.文件名等.第二部分:理论知识学习部分 2.关键字就是Java语言中已经被赋予特定意义 的一些单词. ?常见有:class.public.try.catch.if. float.import.void等. 关键字不做变量名. 3.Java有三种注释的方式:   // 注释内容由//一直到此行结束. /*和*/ 定义一个注释块.  /**开始,*/结束 这种注释方法

201777010217-金云馨《面向对象程序设计(Java)》第二周学习总结

项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/11475377.html 作业学习目标 学习并掌握Java Application程序结构: 学习并掌握Java语言的数据类型与变量: 学会使用Java运算符构造各类表达式: 掌握Java Application输入输出技术: 掌握Java流程控制技术(分支.循环): 掌握Math类.Strin

20182334 2019-2020-1 《数据结构与面向对象程序设计》第五周学习总结

20182334 2019-2020-1 <数据结构与面向对象程序设计>第五周学习总结 教材学习内容总结 第五周主要是在国庆中度过的,也主要学的是第八章的内容,更充实.更饱满. 第八章: 继承:从一个已有的类派生一个新类的过程,目的是为了更快更节约的完成程序.继承会产生父类和子类,他们之间建立了is-a关系.保留字extends说明从已有类中派生一个新类. 在封装和私有的两难境地中,出现了protected修饰符,既可以提供最恰当的封装机制,也保持了其在原来类中可见性修饰符规定的权限.在满足可

20182333 2019-2020-1 《数据结构与面向对象程序设计》第八周学习总结

20182333 2019-2020-1 <数据结构与面向对象程序设计>第八周学习总结 教材学习内容总结 查找 1.查找:是一个过程,即在某个项目组中寻找某一项指定目标元素,或者确定该指定目标并不存在. 2.静态方法:也称为类方法,可以通过类名来调用,无需实例化该类的对象. 在方法声明中,通过使用static修饰符就可以把他声明为静态的. 3.泛型方法:要创建一个泛型方法,只需要在方法头的返回类型前插入一个泛型声明即可,其格式是:修饰符 返回类型 方法名(形参列表) { 方法体 }.例如: p

20182306 2019-2020-1 《数据结构与面向对象程序设计》第八周学习总结

目录 20182306 2019-2020-1 <数据结构与面向对象程序设计>第八周学习总结 教材学习内容总结 教材学习中的问题和解决过程 代码调试中的问题和解决过程 代码托管 上周考试错题总结 结对及互评 评分标准 点评模板: 点评过的同学博客和代码 其他(感悟.思考等,可选) 学习进度条 参考资料 20182306 2019-2020-1 <数据结构与面向对象程序设计>第八周学习总结 教材学习内容总结 查找 线性查找即按顺序从前向后一个一个进行查找,但是为了提高代码运行效率,可

20182308 华罗晗 2019-2020-1 《数据结构与面向对象程序设计》第10周学习总结

20182308 2019-2020-1 <数据结构与面向对象程序设计>第10周学习总结 教材学习内容总结 有关于图的课堂内容: 邻接矩阵.邻接表,图的数组表示法.一个字符串上的数组就可实现数组.需要掌握. 我们简单提到了其他以下几种图:边集数组.无向图邻接表.逆邻接表.十字链表.邻接多重表(比较复杂,老师也没有讲) 图的遍历以及编码实现主要包括以下两大块的内容:前序中序后序的实现:广度优先搜索.深度优先搜索两种搜索方式的实现. 教材学习中的问题和解决过程 问题1:图和树有什么区别?我们说的完

20182332 2019-2020-1 《数据结构与面向对象程序设计》第1周学习总结

20182332 2019-2020-1 <数据结构与面向对象程序设计>第1周学习总结1 教材学习内容总结 1.配置linux 虚拟机.java环境. 2.理解面向对象程序设计,包括属性.方法.封装等概念. Java基本结构,环境变量配置,集成开发环境. JAVA文件编译过程: 1.源文件由编译器编译成字节码(ByteCode) 2.字节码由java虚拟机解释运行. git命令: git init 创建本地版本库: git clone 与远程仓库建立联系: git add .将当前目录下文件添

《数据结构与面向对象程序设计》第1周学习总结

学号 2019-2020-2314 <数据结构与面向对象程序设计>第1周学习总结 教材学习内容总结 1.计算机系统是由软硬件组成的 2.java程序的结构组成(注释.标识符和保留字等) 注:java是大小写敏感的,大写和小写是有区别的 3.程序开发所包含的内容(程序设计语言的等级.编辑器.编译程序.解释程序.开发环境和语法语义) 4.在开发软件的过程中遇到问题时的解决步骤:理解问题.设计方案.考虑方案的选择并优化方案.实现方案.测试方案并修改存在的任何问题. 教材学习中的问题和解决过程 问题1

20182329 2019-2020-1 《数据结构与面向对象程序设计》第1周学习总结

20182329 2019-2020-1 <数据结构与面向对象程序设计>第1周学习总结 教材学习内容总结 git代码托管代码 Java的基本编程 jdb代码调试 教材学习中的问题和解决过程 问题1:在课本自学过程中,有一题是Java中有什么是不可能被识别的,我做错了一道(12345)可以被识别. 问题1解决方案:后来询问学长数字不与命令相匹配时不是有效的标识符,且标识符不能以数字为开头. 问题2:在自己对于课本代码编译时,发现自己main处显示错误 问题2解决方案:一开始我以为是我main的方

《数据结构与面向对象程序设计》第01周学习总结

目录 学号20182323 2019-2020-1 <数据结构与面向对象程序设计>第01周学习总结 教材学习内容总结 教材学习中的问题和解决过程 代码调试中的问题和解决过程 代码托管 上周考试错题总结 结对及互评 点评模板: 点评过的同学博客和代码 其他(感悟.思考等,可选) 学习进度条 参考资料 目录 学号20182323 2019-2020-1 <数据结构与面向对象程序设计>第01周学习总结 教材学习内容总结 学习了java的历史与发展. 学习了一些软件工具,开发环境等. 掌握