201871010104-陈园园《面向对象程序设计(java)》第十七周学习总结

项目 内容
这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/
这个作业要求在哪里 https://www.cnblogs.com/lily-2018/p/11441372.html
作业学习目标

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

(2) 线程综合编程练习

第一部分:总结理论知识

多线程调度
     java提供一个线程调度器来监控程序启动后进入可运行状态的所有线程。线程调度器按照线程的优先级决定应调度那些线程来执行。处于可运行状态的线程首先进入就绪队列排队等候CPU资源,同一时刻在就绪队列中的线程可能有多个。java的多线程系统会给每个线程自动分配一个优先级。

java的线程调度采用优先级的策略:

1)优先级高的先执行,优先级低的后执行。

2)多线程系统会自动为每个线程分配一个人优先级,缺省时,继承其父类的优先级。

3)任务紧急的线程,其优先级较高。

4)同优先级的线程按“先进先出”的队列原则。

Thread类有三个与线程优先级有关的静态量:

MAX_PRIORITY:最大优先权,值为10;

MIN_PRIORITY:最小优先权,值为1;

NORM_PRIORITY:默认优先权,值为5。

调用setPrioritya(int a)重置当前线程的优先级,a取值可以是前述的三个静态量。

调用getPriority()获得当前线程优先级。

下面几种情况下,当前运行线程会放弃CPU:

-线程调用了yield()或s条件变量,以及线程调用sleep()方法;

-抢先式系统下,有高优先级的线程参与调度;

-由于当前线程进行I/O访问、外存读写、等待用户输入等操作导致线程阻塞;或者是为等候一个wait()方法。

守护线程

守护线程是唯一用途是为其他线程提供服务。例如计时线程。

若JVM的运行任务只剩下守护线程时,JVM就退出了。

在一个线程启动之前,调用setaDaemon方法可将线程转换为守护线程(daemon thread)。

例如:setDaemon(true);

用setPrority()方法可以改变线程的优先级。

多线程并发存在问题:

java通过多线程的并发运行提高系统资源利用率,改善系统性能。

存在问题:假设有两个或两个以上的线程共享某个对象,每个线程都调用了改变该对象类状态的方法,会产生什么结果呢?参照实验测试程序三。

多线程并发执行中的问题:

1)多个线程的相对执行顺序不确定。

2)线程执行顺序不确定性会产生执行结果的不确定性。

3)在多线程对共享数据操作时常常会产生不确定性。

线程的同步

多线程并发运行不确定性问题解决方案:引入线程同步机制。

在java中多线程同步方法有两种:

-javaSE5.0中引入ReentrantLock类。

-在共享内存中类方法前加synchronized修饰符。public synchronized static void sub(int m)

有关锁对象和条件对象的关键要点:

锁用来保护代码片段,保证在任何时刻只能有一个线程执行被保护的代码》

锁管理视图进入被保护代码段的线程。

锁可拥有一个或多个相关条件对象。

每个条件对象管理那些已经进入被保护的代码段但还不能运行的线程。

在临界区中使用条件对象的await()、signal()、signalAll()方法实现线程之间的交互。

第二部分:实验测试

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

测试程序1:

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

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

  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();//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. }
  87.  
  88. bank
  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. }
  41.  
  42. SynchBank

运行结果:

测试程序2:

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

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

  1. package synch2;
  2.  
  3. import java.util.*;
  4.  
  5. /**
  6. * A bank with a number of bank accounts that uses synchronization primitives.
  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. * Constructs the bank.
  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. * Transfers money from one account to another.
  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. * Gets the sum of all account balances.
  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. * Gets the number of accounts in the bank.
  59. * @return the number of accounts
  60. */
  61. public int size()
  62. {
  63. return accounts.length;
  64. }
  65. }
  66.  
  67. Bank
  1. package synch2;
  2.  
  3. /**
  4. * This program shows how multiple threads can safely access a data structure,
  5. * using synchronized methods.
  6. * @version 1.31 2015-06-21
  7. * @author Cay Horstmann
  8. */
  9. public class SynchBankTest2
  10. {
  11. public static final int NACCOUNTS = 100;
  12. public static final double INITIAL_BALANCE = 1000;
  13. public static final double MAX_AMOUNT = 1000;
  14. public static final int DELAY = 10;
  15.  
  16. public static void main(String[] args)
  17. {
  18. Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
  19. for (int i = 0; i < NACCOUNTS; i++)
  20. {
  21. int fromAccount = i;
  22. Runnable r = () -> {
  23. try
  24. {
  25. while (true)
  26. {
  27. int toAccount = (int) (bank.size() * Math.random());
  28. double amount = MAX_AMOUNT * Math.random();
  29. bank.transfer(fromAccount, toAccount, amount);
  30. Thread.sleep((int) (DELAY * Math.random()));
  31. }
  32. }
  33. catch (InterruptedException e)
  34. {
  35. }
  36. };
  37. Thread t = new Thread(r);
  38. t.start();
  39. }
  40. }
  41. }
  42.  
  43. SynchBankTest2

运行结果:

测试程序3:

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

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

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

运行结果:

修改程序如下:

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

运行结果:

实验2 编程练习

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

代码如下:

  1. package synch3;
  2. public class Demo {
  3. public static void main(String[] args) {
  4. Mythread mythread = new Mythread();
  5. Thread ticket1 = new Thread(mythread);
  6. Thread ticket2 = new Thread(mythread);
  7. Thread ticket3 = new Thread(mythread);
  8. ticket1.start();
  9. ticket2.start();
  10. ticket3.start();
  11. }
  12. }
  13.  
  14. class Mythread implements Runnable {
  15. int ticket = 1;
  16. boolean flag = true;
  17.  
  18. @Override
  19. public void run() {
  20. while (flag) {
  21. try {
  22. Thread.sleep(500);
  23. } catch (InterruptedException e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. }
  27.  
  28. synchronized (this) {
  29. if (ticket <= 10) {
  30. System.out.println(Thread.currentThread().getName() + "窗口售:第" + ticket + "张票");
  31. ticket++;
  32. }
  33. if (ticket > 10) {
  34. flag = false;
  35. }
  36. }
  37. }
  38. }
  39.  
  40. }

运行结果:

结对照片

实验总结:

本节课继续学习了线程同步技术以及上锁问题,在上节课的基础上更一步加强了对线程的了解。在测试程序中更深一步的理解了理论知识,发现了线程的多变性,希望在接下来的学习中可以更好的运用。继续加油吧!结对编程的过程中,遇到的问题通过一起商量得到了解决 ,也学到了很多知识。

  

201871010104-陈园园《面向对象程序设计(java)》第十七周学习总结的更多相关文章

  1. 201771010134杨其菊《面向对象程序设计java》第九周学习总结

                                                                      第九周学习总结 第一部分:理论知识 异常.断言和调试.日志 1.捕获 ...

  2. 201871010132-张潇潇《面向对象程序设计(java)》第一周学习总结

    面向对象程序设计(Java) 博文正文开头 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cn ...

  3. 扎西平措 201571030332《面向对象程序设计 Java 》第一周学习总结

    <面向对象程序设计(java)>第一周学习总结 正文开头: 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 ...

  4. 201871010124 王生涛《面向对象程序设计JAVA》第一周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://edu.cnblogs.com/campus/xbsf/ ...

  5. 杨其菊201771010134《面向对象程序设计Java》第二周学习总结

    第三章 Java基本程序设计结构 第一部分:(理论知识部分) 本章主要学习:基本内容:数据类型:变量:运算符:类型转换,字符串,输入输出,控制流程,大数值以及数组. 1.基本概念: 1)标识符:由字母 ...

  6. 201871010115——马北《面向对象程序设计JAVA》第二周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

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

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  8. 201871010132——张潇潇《面向对象程序设计JAVA》第二周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

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

    一.理论知识部分 1.标识符由字母.下划线.美元符号和数字组成, 且第一个符号不能为数字.标识符可用作: 类名.变量名.方法名.数组名.文件名等.第二部分:理论知识学习部分 2.关键字就是Java语言 ...

  10. 马凯军201771010116《面向对象与程序设计Java》第九周学习总结

    一.理论知识部分 异常.日志.断言和调试 1.异常:在程序的执行过程中所发生的异常事件,它中断指令的正常执行. 2.Java的异常处理机制可以控制程序从错误产生的位置转移到能够进行错误处理的位置. 3 ...

随机推荐

  1. mongo fork

    logpath=../log/mongodb.log logappend=false dbpath=/hejing/data/db fork=true

  2. GIT SSH-KEY配置以及问题解决

    GIT SSH-KEY 生成 我们在使用git的时候需要生成ssh key,我在这里说一下生成key和一些个性化操作,如:保存key的位置,如何解决Could not open a connectio ...

  3. 使用foreach的禁忌

    List<String> list = new ArrayList<>(); Iterator<String> iterator = list.iterator() ...

  4. php 连接sqlserver

    本地环境windows 10+phpstudy2016+ SQL Server 2008 R2 x86+php7.0查看自己sql server 多少位可以在新建查询里输入 select @@VERS ...

  5. django时区与时间差的问题

    时区的正确配置方式: # 这里还可以配置成中文 一般用不到 LANGUAGE_CODE = 'en-us' # TIME_ZONE = 'UTC' TIME_ZONE = 'Asia/Shanghai ...

  6. 怎样单独遍历NodeList的键、值和键值对

    1. 单独遍历键: NodeList.prototype.keys(); 2. 单独遍历值: NodeList.prototype.values(); 3. 遍历键值对: NodeList.proto ...

  7. javascript——== 和===的区别

    == 等于 === 全等(值和类型) console.log(5==5);//true console.log(5=="5");//true console.log(5===5); ...

  8. C#委托的定义 以及使用方式详解,更简单的理解委托。

    委托的声明及定义: 委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使得 ...

  9. Sublime Text 3配置浏览默认路径为localhost

    1.在 Sublime Text 3 中,安装 SideBarEnhancements 侧边栏增强插件.(注意:安装插件之前需要安装包管理工具,参考这里) 2.SideBarEnhancements ...

  10. C++ STL用法总结(持续更新)

    Vector 动态数组 https://www.cnblogs.com/zhonghuasong/p/5975979.html lower_bound&&upper_bound htt ...