刘志梅201771010115.《面向对象程序设计(java)》第十七周学习总结
实验十七 线程同步控制
实验时间 2018-12-10
1、实验理论知识
多线程
多线程是进程执行过程中产生的多条执行线索。
进程
线程是比进程执行更小的单位。线程不能独立存在,必须存在于进程中,同一进程的各线程间共享进程空间的数据。每个线程有它自身的产生、存在和消亡的过程, 是一个动态的概念。线程创建、销毁和切换的负荷远小于进程,又称 为轻量级进程(lightweight process)。
Java实现多线程
-创建Thread类的子类
-在程序中定义实现Runnable接口的类
用Thread类的子类创建线程
首先需从Thread类派生出一个子类,在该子类中 重写run()方法。
class hand extends Thread { public void run() {……} }
然后用创建该子类的对象
Lefthand left=new Lefthand();
Righthand right=new Righthand();
最后用start()方法启动线程
left.start();
right.start();
用Runnable()接口实现线程
首先设计一个实现Runnable接口的类;
然后在类中根据需要重写run方法;
再创建该类对象,以此对象为参数建立Thread 类的对象;
调用Thread类对象的start方法启动线程,将 CPU执行权转交到run方法。
线程的终止:调用interrupt()方法。
多线程并发运行不确定性问题解决方案:引入线 程同步机制,使得另一线程要使用该方法,就只 能等待。
在Java中解决多线程同步问题的方法有两种: - Java SE 5.0中引入ReentrantLock类。 - 在共享内存的类方法前加synchronized修饰符。
2、实验内容和步骤
实验1:测试程序并进行代码注释。
测试程序1:
l 在Elipse环境下调试教材651页程序14-7,结合程序运行结果理解程序;
l 掌握利用锁对象和条件对象实现的多线程同步技术。
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//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);//调用initialBalance生成锁对象属性
bankLock = new ReentrantLock();
sufficientFunds = bankLock.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();//用锁对象生成条件对象sufficientFunds
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 = ; 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;
}
}
/**
* 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 = ;
public static final double INITIAL_BALANCE = ;
public static final double MAX_AMOUNT = ;
public static final int DELAY = ; public static void main(String[] args)
{
Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
for (int i = ; 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();
}
}
}

测试程序2:
l 在Elipse环境下调试教材655页程序14-8,结合程序运行结果理解程序;
l 掌握synchronized在多线程同步中的应用。
/**
* 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 = ;
public static final double INITIAL_BALANCE = ;
public static final double MAX_AMOUNT = ;
public static final int DELAY = ; public static void main(String[] args)
{
Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);//创建一个银行对象
for (int i = ; 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();//线程处于可运行状态
}
}
}
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();//唤醒所有等待的线程
} /**
* Gets the sum of all account balances.
* @return the total balance
*/
public synchronized double getTotalBalance()
{
double sum = ; 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;
}
}

测试程序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(); } } |
class Cbank
{
private static int s=;//当类加载时s赋值为2000
public static void sub(int m)
{
int temp=s;
temp=temp-m;
try {
Thread.sleep((int)(*Math.random()));
}
catch (InterruptedException e) { }//捕获中断异常
s=temp;
System.out.println("s="+s);
}
} class Customer extends Thread//继承
{
public void run()//中值返回
{
for( int i=; i<=; i++)
Cbank.sub();
}
}
public class Thread3
{
public static void main(String args[])
{
Customer customer1 = new Customer();//把变量customer1的值设置为分配给新的Customer对象的内部地址
Customer customer2 = new Customer();
customer1.start();
customer2.start();
}
}

修改后的代码:
class Cbank
{
private static int s=;
public synchronized static void sub(int m)
{
int temp=s;
temp=temp-m;
try {
Thread.sleep((int)(*Math.random()));
}
catch (InterruptedException e) { }
s=temp;
System.out.println("s="+s);
}
}
class Customer extends Thread
{
public void run()
{
for( int i=; i<=; i++)
Cbank.sub();
}
}
public class Thread3
{
public static void main(String args[])
{
Customer customer1 = new Customer();
Customer customer2 = new Customer();
customer1.start();
customer2.start();
}
}

实验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张票
package tracket;
public class tracket {
public static void main(String[] args) {
Mythread mythread = new Mythread();
Thread t1 = new Thread(mythread);//实例化了一个Thread对象thread1
Thread t2 = new Thread(mythread);
Thread t3 = new Thread(mythread);
t1.start();//线程启动
t2.start();
t3.start();
}
}
class Mythread implements Runnable {
int t = ;
boolean flag = true;
@Override
public void run() {
// TODO Auto-generated method stub
while (flag) {
try {
Thread.sleep();//休眠时间500毫秒
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
synchronized (this) {
if (t <= ) {
System.out.println(Thread.currentThread().getName() + "窗口售:第" + t + "张票");
t++;
}
if (t > ) {
flag = false;
}
}
}
}
}

实验总结:本周实验学习了线程的同步,对线程有了更能进一步的学习,最后的编程的练习题通过学长的讲解以及演示,代码语句的解释,深入了解线程同步问题;本周也是最后一周的实验,这学期通过老师和学长的教学学习到了不少java的知识,非常感谢。
刘志梅201771010115.《面向对象程序设计(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/ 这个作业的要求在哪里 ...
- 杨其菊201771010134《面向对象程序设计Java》第二周学习总结
第三章 Java基本程序设计结构 第一部分:(理论知识部分) 本章主要学习:基本内容:数据类型:变量:运算符:类型转换,字符串,输入输出,控制流程,大数值以及数组. 1.基本概念: 1)标识符:由字母 ...
- 201871010124 王生涛《面向对象程序设计JAVA》第一周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://edu.cnblogs.com/campus/xbsf/ ...
- 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 ...
随机推荐
- SharePoint 2013 新特性 (三) 破改式 —— 设计管理器的使用 [1.设备通道]
首先,哥们儿们会问,为啥要有设计管理器呢,不是原来就可以编辑页面了么,原来那个编辑不了模板页和布局页,也不能打包,而且也看不到具体HTML代码,不能编辑CSS,当然,你安装的SharePoint De ...
- easyui Tree模拟级联勾选cascadeCheck,节点选择,父节点自动选中,节点取消,父节点自动取消选择,节点选择,所有子节点全部选择,节点取消,所有子节点全部取消勾选
最近项目中用到easyui tree,发现tree控件的cascadeCheck有些坑,不像miniui 的tree控件,级联勾选符合业务需求,所以就自己重新改写了onCheck事件,符合业务需求.网 ...
- jQuery-4.动画篇---上卷下拉效果
jQuery中下拉动画slideDown 对于隐藏的元素,在将其显示出来的过程中,可以对其进行一些变化的动画效果.之前学过了show方法,show方法在显示的过程中也可以有动画,但是.show()方法 ...
- 聊一聊 redux 异步流之 redux-saga
让我惊讶的是,redux-saga 的作者竟然是一名金融出身的在一家房地产公司工作的员工(让我想到了阮老师...),但是他对写代码有着非常浓厚的热忱,喜欢学习和挑战新的事物,并探索新的想法.恩,牛逼的 ...
- Python全栈之路----常用模块----re 模块
正则表达式就是字符串的匹配规则,在多数编程语言里都有相应的支持,python里对应的模块是 re. re的匹配语法有以下几种 re.match 从头开始匹配 re.search 匹配包含 re.fin ...
- 解题报告 『[USACO08NOV]Mixed Up Cows(状压动规)』
原题地址 观察数据范围:4 ≤ N ≤ 16. 很明显,这是一道状压DP. 定义:dp[i][j]表示队尾为奶牛i,当前含奶牛的状态为j,共有多少组符合条件的队伍. 代码实现如下: #include ...
- javascript 4.2
element.value="......"也可以为属性设置新的值 setAttribute()方法是“第一级DOM”的组成部分之一,DOM是适用于多种环境和多种程序设计语言的通用 ...
- creator Box2d的相关物理问题
项目的屏幕配置为 1152*640,没有对这个数值调整来测试质量的除数1024会不会变化 m = h * w / 1024 (m 质量,h 物体高度,w 物体宽度) g = 0, -320 ( ( ...
- jQuery汇总
closest() 方法返回被选元素的第一个祖先元素. $("span").closest("ul")返回 <span> 的第一个祖先元素,是一个 ...
- TypeScript 学习资料
TypeScript 学习资料: 学习资料 网址 TypeScript Handbook(中文版)(推荐) https://m.runoob.com/manual/gitbook/TypeScript ...