201871010104-陈园园《面向对象程序设计(java)》第十七周学习总结
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) 掌握利用锁对象和条件对象实现的多线程同步技术。
- package synch;
- import java.util.*;
- import java.util.concurrent.locks.*;
- /**
- * A bank with a number of bank accounts that uses locks for serializing access.
- * @version 1.30 2004-08-01
- * @author Cay Horstmann
- */
- public class Bank
- {
- private final double[] accounts;
- private Lock bankLock;
- private Condition sufficientFunds;
- /**
- * Constructs the bank.
- * @param n the number of accounts
- * @param initialBalance the initial balance for each account
- */
- public Bank(int n, double initialBalance)
- {
- accounts = new double[n];
- Arrays.fill(accounts, initialBalance);
- bankLock = new ReentrantLock();//锁对象初始化
- sufficientFunds = bankLock.newCondition();//newCondition方法生成锁对象的条件对象
- }
- /**
- * Transfers money from one account to another.
- * @param from the account to transfer from
- * @param to the account to transfer to
- * @param amount the amount to transfer
- */
- public void transfer(int from, int to, double amount) throws InterruptedException
- {//加锁
- bankLock.lock();
- try
- {
- while (accounts[from] < amount)
- sufficientFunds.await();//将线程放到条件的等待集中
- System.out.print(Thread.currentThread());
- accounts[from] -= amount;
- System.out.printf(" %10.2f from %d to %d", amount, from, to);
- accounts[to] += amount;
- System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
- sufficientFunds.signalAll();//解除该条件的等待集中随机的所有线程的阻塞状态
- }
- finally
- {
- bankLock.unlock();//释放这个锁
- }
- }
- /**
- * Gets the sum of all account balances.
- * @return the total balance
- */
- public double getTotalBalance()
- {
- bankLock.lock();
- try
- {
- double sum = 0;
- for (double a : accounts)
- sum += a;
- return sum;
- }
- finally
- {
- bankLock.unlock();
- }
- }
- /**
- * Gets the number of accounts in the bank.
- * @return the number of accounts
- */
- public int size()
- {
- return accounts.length;
- }
- }
- bank
- package synch;
- /**
- * This program shows how multiple threads can safely access a data structure.
- * @version 1.31 2015-06-21
- * @author Cay Horstmann
- */
- public class SynchBankTest
- { //定义四个公共属性
- public static final int NACCOUNTS = 100;
- public static final double INITIAL_BALANCE = 1000;
- public static final double MAX_AMOUNT = 1000;
- public static final int DELAY = 10;
- public static void main(String[] args)
- {
- Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
- for (int i = 0; i < NACCOUNTS; i++)
- {
- int fromAccount = i;
- Runnable r = () -> {
- try//抛出异常
- {
- while (true)
- {
- int toAccount = (int) (bank.size() * Math.random());
- double amount = MAX_AMOUNT * Math.random();
- bank.transfer(fromAccount, toAccount, amount);
- Thread.sleep((int) (DELAY * Math.random()));
- }
- }
- catch (InterruptedException e)
- {
- }
- };
- Thread t = new Thread(r);
- t.start();
- }
- }
- }
- SynchBank
运行结果:
测试程序2:
1) 在Elipse环境下调试教材655页程序14-8,结合程序运行结果理解程序;
2)掌握synchronized在多线程同步中的应用。
- package synch2;
- import java.util.*;
- /**
- * A bank with a number of bank accounts that uses synchronization primitives.
- * @version 1.30 2004-08-01
- * @author Cay Horstmann
- */
- public class Bank
- {
- private final double[] accounts;
- /**
- * Constructs the bank.
- * @param n the number of accounts
- * @param initialBalance the initial balance for each account
- */
- public Bank(int n, double initialBalance)
- {
- accounts = new double[n];
- Arrays.fill(accounts, initialBalance);
- }
- /**
- * Transfers money from one account to another.
- * @param from the account to transfer from
- * @param to the account to transfer to
- * @param amount the amount to transfer
- */
- public synchronized void transfer(int from, int to, double amount) throws InterruptedException
- {
- while (accounts[from] < amount)
- wait();
- System.out.print(Thread.currentThread());
- accounts[from] -= amount;
- System.out.printf(" %10.2f from %d to %d", amount, from, to);
- accounts[to] += amount;
- System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
- notifyAll();//解除那些在该对象上调用wait方法的线程的阻塞状态
- }
- /**
- * Gets the sum of all account balances.
- * @return the total balance
- */
- public synchronized double getTotalBalance()
- {//计算过程
- double sum = 0;
- for (double a : accounts)
- sum += a;
- return sum;
- }
- /**
- * Gets the number of accounts in the bank.
- * @return the number of accounts
- */
- public int size()
- {
- return accounts.length;
- }
- }
- Bank
- package synch2;
- /**
- * This program shows how multiple threads can safely access a data structure,
- * using synchronized methods.
- * @version 1.31 2015-06-21
- * @author Cay Horstmann
- */
- public class SynchBankTest2
- {
- public static final int NACCOUNTS = 100;
- public static final double INITIAL_BALANCE = 1000;
- public static final double MAX_AMOUNT = 1000;
- public static final int DELAY = 10;
- public static void main(String[] args)
- {
- Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
- for (int i = 0; i < NACCOUNTS; i++)
- {
- int fromAccount = i;
- Runnable r = () -> {
- try
- {
- while (true)
- {
- int toAccount = (int) (bank.size() * Math.random());
- double amount = MAX_AMOUNT * Math.random();
- bank.transfer(fromAccount, toAccount, amount);
- Thread.sleep((int) (DELAY * Math.random()));
- }
- }
- catch (InterruptedException e)
- {
- }
- };
- Thread t = new Thread(r);
- t.start();
- }
- }
- }
- SynchBankTest2
运行结果:
测试程序3:
1)在Elipse环境下运行以下程序,结合程序运行结果分析程序存在问题;
2)尝试解决程序中存在问题。
- 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();
- }
- }
运行结果:
修改程序如下:
- package test2;
- class Cbank
- {
- private static int s=2000;
- public synchronized 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();
- }
- }
运行结果:
实验2 编程练习
利用多线程及同步方法,编写一个程序模拟火车票售票系统,共3个窗口,卖10张票,程序输出结果类似(程序输出不唯一,可以是其他类似结果)。
代码如下:
- package synch3;
- public class Demo {
- public static void main(String[] args) {
- Mythread mythread = new Mythread();
- Thread ticket1 = new Thread(mythread);
- Thread ticket2 = new Thread(mythread);
- Thread ticket3 = new Thread(mythread);
- ticket1.start();
- ticket2.start();
- ticket3.start();
- }
- }
- class Mythread implements Runnable {
- int ticket = 1;
- boolean flag = true;
- @Override
- public void run() {
- while (flag) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- synchronized (this) {
- if (ticket <= 10) {
- System.out.println(Thread.currentThread().getName() + "窗口售:第" + ticket + "张票");
- ticket++;
- }
- if (ticket > 10) {
- flag = false;
- }
- }
- }
- }
- }
运行结果:
结对照片
实验总结:
本节课继续学习了线程同步技术以及上锁问题,在上节课的基础上更一步加强了对线程的了解。在测试程序中更深一步的理解了理论知识,发现了线程的多变性,希望在接下来的学习中可以更好的运用。继续加油吧!结对编程的过程中,遇到的问题通过一起商量得到了解决 ,也学到了很多知识。
201871010104-陈园园《面向对象程序设计(java)》第十七周学习总结的更多相关文章
- 201771010134杨其菊《面向对象程序设计java》第九周学习总结
第九周学习总结 第一部分:理论知识 异常.断言和调试.日志 1.捕获 ...
- 201871010132-张潇潇《面向对象程序设计(java)》第一周学习总结
面向对象程序设计(Java) 博文正文开头 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cn ...
- 扎西平措 201571030332《面向对象程序设计 Java 》第一周学习总结
<面向对象程序设计(java)>第一周学习总结 正文开头: 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 ...
- 201871010124 王生涛《面向对象程序设计JAVA》第一周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://edu.cnblogs.com/campus/xbsf/ ...
- 杨其菊201771010134《面向对象程序设计Java》第二周学习总结
第三章 Java基本程序设计结构 第一部分:(理论知识部分) 本章主要学习:基本内容:数据类型:变量:运算符:类型转换,字符串,输入输出,控制流程,大数值以及数组. 1.基本概念: 1)标识符:由字母 ...
- 201871010115——马北《面向对象程序设计JAVA》第二周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- 201777010217-金云馨《面向对象程序设计(Java)》第二周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- 201871010132——张潇潇《面向对象程序设计JAVA》第二周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- 201771010123汪慧和《面向对象程序设计Java》第二周学习总结
一.理论知识部分 1.标识符由字母.下划线.美元符号和数字组成, 且第一个符号不能为数字.标识符可用作: 类名.变量名.方法名.数组名.文件名等.第二部分:理论知识学习部分 2.关键字就是Java语言 ...
- 马凯军201771010116《面向对象与程序设计Java》第九周学习总结
一.理论知识部分 异常.日志.断言和调试 1.异常:在程序的执行过程中所发生的异常事件,它中断指令的正常执行. 2.Java的异常处理机制可以控制程序从错误产生的位置转移到能够进行错误处理的位置. 3 ...
随机推荐
- mongo fork
logpath=../log/mongodb.log logappend=false dbpath=/hejing/data/db fork=true
- GIT SSH-KEY配置以及问题解决
GIT SSH-KEY 生成 我们在使用git的时候需要生成ssh key,我在这里说一下生成key和一些个性化操作,如:保存key的位置,如何解决Could not open a connectio ...
- 使用foreach的禁忌
List<String> list = new ArrayList<>(); Iterator<String> iterator = list.iterator() ...
- php 连接sqlserver
本地环境windows 10+phpstudy2016+ SQL Server 2008 R2 x86+php7.0查看自己sql server 多少位可以在新建查询里输入 select @@VERS ...
- django时区与时间差的问题
时区的正确配置方式: # 这里还可以配置成中文 一般用不到 LANGUAGE_CODE = 'en-us' # TIME_ZONE = 'UTC' TIME_ZONE = 'Asia/Shanghai ...
- 怎样单独遍历NodeList的键、值和键值对
1. 单独遍历键: NodeList.prototype.keys(); 2. 单独遍历值: NodeList.prototype.values(); 3. 遍历键值对: NodeList.proto ...
- javascript——== 和===的区别
== 等于 === 全等(值和类型) console.log(5==5);//true console.log(5=="5");//true console.log(5===5); ...
- C#委托的定义 以及使用方式详解,更简单的理解委托。
委托的声明及定义: 委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使得 ...
- Sublime Text 3配置浏览默认路径为localhost
1.在 Sublime Text 3 中,安装 SideBarEnhancements 侧边栏增强插件.(注意:安装插件之前需要安装包管理工具,参考这里) 2.SideBarEnhancements ...
- C++ STL用法总结(持续更新)
Vector 动态数组 https://www.cnblogs.com/zhonghuasong/p/5975979.html lower_bound&&upper_bound htt ...