常惠琢 201771010102《面向对象程序设计(java)》第十七周学习总结
Posted hongyanohongyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常惠琢 201771010102《面向对象程序设计(java)》第十七周学习总结相关的知识,希望对你有一定的参考价值。
实验十七 线程同步控制
实验时间 2018-12-10
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.*;//导入locks包 5 6 /** 7 * 具有多个银行帐户的银行,使用锁序列化访问 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;//扩张的两个私有属性lock and Condition的一个锁对象一个条件对象 16 17 /** 18 * 建设银行。 19 * @param 账号 20 * @param 每个账户的初始余额 21 */ 22 public Bank(int n, double initialBalance) 23 { 24 accounts = new double[n];//n个账户 25 Arrays.fill(accounts, initialBalance);//每个账户初始资金为1000元 26 bankLock = new ReentrantLock();//建立锁对象(避免线程共享的bank对象内容发生混乱) 27 sufficientFunds = bankLock.newCondition();//建立条件对象(便于得到锁对象的线程在不能做有用的工作时对该线程进行处理) 28 } 29 30 /** 31 * 把钱从一个账户转到另一个账户 32 * @param 从账户转账 33 * @param 转到要转账的账户 34 * @param 转账金额 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();//unlock()解锁 lock上锁 53 } 54 } 55 56 /** 57 * 获取所有帐户余额的总和。 58 * @return 总余额 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 * 获取银行中的帐户数量。 80 * @return 账号 81 */ 82 public int size() 83 { 84 return accounts.length; 85 } 86 }
1 package synch; 2 3 /** 4 * 这个程序显示了多个线程如何安全地访问数据结构 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);//调用了Thread(Runnable target)方法。且父类对象变量指向子类对象。 37 t.start();//使线程处于可运行状态 38 } 39 } 40 }
测试程序2:
l 在Elipse环境下调试教材655页程序14-8,结合程序运行结果理解程序;
l 掌握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(); 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 }
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 }
测试程序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 public class Thread3 2 { 3 public static void main(String args[]) 4 { 5 Customer customer1 = new Customer(); 6 Customer customer2 = new Customer(); 7 customer1.start(); 8 customer2.start(); 9 } 10 }
1 class Customer extends Thread 2 { 3 public void run() 4 { 5 for( int i=1; i<=4; i++) 6 Cbank.sub(100); 7 } 8 }
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 }
实验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 import java.awt.geom.FlatteningPathIterator; 2 3 public class Demo { 4 5 public static void main(String[] args) { 6 Myrhread myrhread=new Myrhread(); 7 Thread t1 = new Thread(myrhread); 8 Thread t2 = new Thread(myrhread); 9 Thread t3 = new Thread(myrhread); 10 t1.start(); 11 t2.start(); 12 t3.start(); 13 } 14 15 } 16 class Myrhread implements Runnable{ 17 int t=1; 18 boolean flag =true; 19 @Override 20 public void run() { 21 while (flag) { 22 try { 23 Thread.sleep(500); 24 } catch (InterruptedException e) { 25 // TODO Auto-generated catch block 26 e.printStackTrace(); 27 } 28 synchronized (this) { 29 if(t<=10) { 30 System.out.println(Thread.currentThread().getName()+"窗口售:第"+t+"张票"); 31 t++; 32 } 33 if(t>10) { 34 flag=false; 35 } 36 37 } 38 39 } 40 41 } 42 43 }
实验总结:
这次实验很少,最后一个程序的编程也学到了很多东西,比如unlock()解锁 , lock上锁等。
以上是关于常惠琢 201771010102《面向对象程序设计(java)》第十七周学习总结的主要内容,如果未能解决你的问题,请参考以下文章
201771010102 常惠琢 《2018面向对象程序设计(Java)》第9周学习总结
常惠琢 201771010102《面向对象程序设计(java)》第七周学习总结
常惠琢 201771010102《面向对象程序设计(java)》第十七周学习总结
201771010102 常惠琢 《2018面向对象程序设计(Java)》第11周学习总结