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 ...
随机推荐
- Java学习笔记-Java中的常用类
Java中有很多类是很常用的,此处列举System,Runtime,Date,Calendar,Math System System:类中的方法和属性都是静态的 字段摘要 static PrintSt ...
- 高并发网络编程之epoll详解(转载)
高并发网络编程之epoll详解(转载) 转载自:https://blog.csdn.net/shenya1314/article/details/73691088 在linux 没有实现epoll事件 ...
- SpreadJS V13.0发布,聚焦表单设计与数据交互,让您的工作效率突飞猛进!
纯前端表格控件SpreadJS,是一款成功应用于华为.招商银行.天弘基金.苏宁易购等国内外知名企业的前端开发工具,其带来的价值不仅体现在帮助开发人员在其Web应用程序中快速构建 Web Excel . ...
- Kafka主题体系架构-复制、故障转移和并行处理
本文讨论了Kafka主题的体系架构,讨论了如何将分区用于故障转移和并行处理. Kafka主题,日志和分区 Kafka将主题存储在日志中.主题日志分为多个分区.Kafka将日志的分区分布在多个服务器或磁 ...
- RSA加密-解密以及解决超长内容加密失败解决
加解密(没有使用到证书):https://blog.csdn.net/qy20115549/article/details/83105736 生成证书网站:https://blog.csdn.net/ ...
- Java开发自动售货机
1:先写一个类,包括商品的基本属性 package com.xt.java.base25; public class Goods { private int ID; private String na ...
- Python(十) —— 多进程多线程
进程线程概念 进程理解为一个程序,具体完成工作的是线程.比如说启动一个 QQ ,QQ 程序里面可以聊天,设置,查找好友等,那么这些功能就理解成各个线程,也就是单进程多线程的一个模式.进程理解成人脑子, ...
- 排好序的数组中,找出两数之和为m的所有组合
public static void main(String[] args) { int[] a = {1,2,2,3,3,4,5,6}; int m = 6; normal(a, m); } //正 ...
- 3 java 笔记
1 垃圾回收机制能够很好地提高编程效率 2 垃圾回机制保护程序的完成性 3 面向对象的三种基本特征:继承,封装,多态 4 面向对象的方式:OOA(面向对象的分析),OOD(面向对象的设计)和OOP(面 ...
- 解决docker pull 速度慢问题
解决docker pull 速度慢问题 将docker镜像源修改为国内的: 在 /etc/docker/daemon.json 文件中添加以下参数(没有该文件则新建): { "registr ...