201871010135 张玉晶 《面向对象程序设计(java)》第十七周学习总结
项目 |
内容 |
这个作业属于哪个课程 |
https://www.cnblogs.com/nwnu-daizh/ |
这个作业的要求在哪里 |
https://www.cnblogs.com/zyja/p/12081073.html |
作业学习目标 |
1) 理解和掌握线程的优先级属性及调度方法; (2) 掌握线程同步的概念及实现技术; (3) Java线程综合编程练习 |
一、总结理论知识
1. 多线程并发存在问题
• Java通过多线程的并发运行提高系统资源利用率,改善系统性能。
• 多个线程的相对执行顺序不确定性。
• 线程执行顺序不确定性会产生执行结果的不确定性。
• 在多线程对共享数据操作时常常会产生不确定性。
2. 线程的同步
• 多线程并发不确定性问题解决方案 : 引入线程同步机制
• 在Java中多线程同步方法有两种:
-- JavaSE5.0中引入ReentrantLock类
-- 在共享内存的类方法前加 synchronized 修饰符。
解决方案一:
• 锁对象与条件对象
➢ 锁用来保护代码片段,保证任何时刻只能有一个线程被保护执行的代码;
➢ 锁管理试图进入被保护的代码段的线程;
➢ 锁可拥有一个或多个相关的条件对象;
➢每个条件对象管理那些已经进入被保护得到代码段但还不能运行的线程;
• 在临界区中使用条件对象的await()、signal()、signalAll()方法实现线程之间的交互:
➢一个线程在临界区时,可能根据问题的需要,必须使用锁对象的await()方法使本线程等待,暂时让出CPU的使用权,并允许其他线程使用这个同步方法;
➢ 线程若退出临界区,应用signal()方法随机的选择一个线程解除其阻塞状态;
➢线程若退出临界区,执行notifyAll()方法通知所有由于等待该临界区的线程结束等待。
解决方案二:synchronized关键字
• synchronized关键字作用:
➢ 某个类内方法用synchronized修饰符后,该方法被称为同步线程;
➢ 只要某个线程正在访问同步方法,其他线程欲要访问同步方法就会被阻塞,直至线程从同步方法返回前唤醒被阻塞线程,其他线程方法可能进入同步方法;
二、实验内容和步骤
实验1:测试程序并进行代码注释。
测试程序1:
在Elipse环境下调试教材651页程序14-7,结合程序运行结果理解程序;
掌握利用锁对象和条件对象实现的多线程同步技术。
1 package synch; 2 import java.util.*; 3 import java.util.concurrent.locks.*; 4 5 /** 6 * A bank with a number of bank accounts that uses locks for serializing access. 7 * @version 1.30 2004-08-01 8 * @author Cay Horstmann 9 */ 10 public class Bank 11 { 12 private final double[] accounts; 13 private Lock bankLock; //锁 14 private Condition sufficientFunds;//条件对象 15 16 /** 17 * Constructs the bank. 18 * @param n the number of accounts 19 * @param initialBalance the initial balance for each account 20 */ 21 public Bank(int n, double initialBalance) 22 { 23 accounts = new double[n]; 24 Arrays.fill(accounts, initialBalance); 25 bankLock = new ReentrantLock();//构建一个可以被用来保护临界区的可重入锁 26 sufficientFunds = bankLock.newCondition();//设置一个条件对象 27 } 28 29 /** 30 * Transfers money from one account to another. 31 * @param from the account to transfer from 32 * @param to the account to transfer to 33 * @param amount the amount to transfer 34 */ 35 public void transfer(int from, int to, double amount) throws InterruptedException 36 { 37 bankLock.lock();//加锁,如果锁同时被另一个线程拥有,则发生阻塞 38 try 39 { 40 while (accounts[from] < amount) //当账户余额不足时 41 sufficientFunds.await();//余额不足,当前线程被阻塞 42 System.out.print(Thread.currentThread()); 43 accounts[from] -= amount; 44 System.out.printf(" %10.2f from %d to %d", amount, from, to); 45 accounts[to] += amount; 46 System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); 47 sufficientFunds.signalAll();//重新激活了阻塞的所有线程 48 } 49 finally 50 { 51 bankLock.unlock();//释放这个锁 52 } 53 } 54 55 /** 56 * Gets the sum of all account balances. 57 * @return the total balance 58 */ 59 public double getTotalBalance() 60 { 61 bankLock.lock();//加锁 62 try 63 { 64 double sum = 0; 65 66 for (double a : accounts) 67 sum += a; 68 69 return sum; 70 } 71 finally 72 { 73 bankLock.unlock();//释放锁 74 } 75 } 76 77 /** 78 * Gets the number of accounts in the bank. 79 * @return the number of accounts 80 */ 81 public int size() 82 { 83 return accounts.length; 84 } 85 }
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 = () -> { // //Runnable接口实现创建线程 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); //调用transfer方法在同行之间进行转账 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 }
运行结果如下:
测试程序2:
在Elipse环境下调试教材655页程序14-8,结合程序运行结果理解程序;
掌握synchronized在多线程同步中的应用。
1 import java.util.*; 2 3 /** 4 * A bank with a number of bank accounts that uses synchronization primitives. 5 * @version 1.30 2004-08-01 6 * @author Cay Horstmann 7 */ 8 public class Bank 9 { 10 private final double[] accounts; 11 12 /** 13 * Constructs the bank. 14 * @param n the number of accounts 15 * @param initialBalance the initial balance for each account 16 */ 17 public Bank(int n, double initialBalance) 18 { 19 accounts = new double[n]; 20 Arrays.fill(accounts, initialBalance); 21 } 22 23 /** 24 * Transfers money from one account to another. 25 * @param from the account to transfer from 26 * @param to the account to transfer to 27 * @param amount the amount to transfer 28 */ 29 public synchronized void transfer(int from, int to, double amount) throws InterruptedException 30 { 31 while (accounts[from] < amount) 32 wait();//线程进入等待状态 33 System.out.print(Thread.currentThread()); 34 accounts[from] -= amount; 35 System.out.printf(" %10.2f from %d to %d", amount, from, to); 36 accounts[to] += amount; 37 System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); 38 notifyAll();//解除在该对象上调用wait方法的线程的阻塞状态 39 } 40 41 /** 42 * Gets the sum of all account balances. 43 * @return the total balance 44 */ 45 public synchronized double getTotalBalance() 46 { 47 double sum = 0; 48 49 for (double a : accounts) 50 sum += a; 51 52 return sum; 53 } 54 55 /** 56 * Gets the number of accounts in the bank. 57 * @return the number of accounts 58 */ 59 public int size() 60 { 61 return accounts.length; 62 } 63 }
1 /** 2 * This program shows how multiple threads can safely access a data structure, 3 * using synchronized methods. 4 * @version 1.31 2015-06-21 5 * @author Cay Horstmann 6 */ 7 public class SynchBankTest2 8 { 9 public static final int NACCOUNTS = 100; 10 public static final double INITIAL_BALANCE = 1000; 11 public static final double MAX_AMOUNT = 1000; 12 public static final int DELAY = 10; 13 14 public static void main(String[] args) 15 { 16 Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE); 17 for (int i = 0; i < NACCOUNTS; i++) 18 { 19 int fromAccount = i; 20 Runnable r = () -> { //Runnable接口创建线程 21 try 22 { 23 while (true) 24 { 25 int toAccount = (int) (bank.size() * Math.random()); 26 double amount = MAX_AMOUNT * Math.random(); 27 bank.transfer(fromAccount, toAccount, amount); //调用transfer方法在同行之间进行转账 28 Thread.sleep((int) (DELAY * Math.random())); //随机产生0-10毫秒之间的一个数,调用sleep方法睡眠。 29 } 30 } 31 catch (InterruptedException e) 32 { 33 } 34 }; 35 Thread t = new Thread(r); 36 t.start();//启动线程 37 } 38 } 39 }
运行结果如下:
测试程序3:
在Elipse环境下运行以下程序,结合程序运行结果分析程序存在问题;
尝试解决程序中存在问题。
1 package synch; 2 3 class Cbank 4 { 5 private static int s=2000; 6 public static void sub(int m) 7 { 8 int temp=s; 9 temp=temp-m; 10 try { 11 Thread.sleep((int)(1000*Math.random())); 12 } 13 catch (InterruptedException e) { } 14 s=temp; 15 System.out.println("s="+s); 16 } 17 } 18 19 20 class Customer extends Thread 21 { 22 public void run() 23 { 24 for( int i=1; i<=4; i++) 25 Cbank.sub(100); 26 } 27 } 28 public class Thread3 29 { 30 public static void main(String args[]) 31 { 32 Customer customer1 = new Customer(); 33 Customer customer2 = new Customer(); 34 customer1.start(); 35 customer2.start(); 36 } 37 }
运行结果如下:
问题:多个线程同时进行,线程执行顺序不确定从而产生的结果会有不确定性。
解决方法:引入线程同步机制
改进后的代码:在共享内存中的类方法前加 synchronized 修饰符
1 package synch; 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 19 class Customer extends Thread 20 { 21 public void run() 22 { 23 for( int i=1; i<=4; i++) 24 Cbank.sub(100); 25 } 26 } 27 public class Thread3 28 { 29 public static void main(String args[]) 30 { 31 Customer customer1 = new Customer(); 32 Customer customer2 = new Customer(); 33 customer1.start(); 34 customer2.start(); 35 } 36 }
运行结果如下:
实验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 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 }
运行结果如下:
结对照片如下:
实验总结:本周学了多线程并发存在的问题,解决方案是:引入线程同步机制。有两种方法:JavaSE5.0中引入ReentrantLock类、在共享内存的类方法前加 synchronized 修饰符。结对编程还是有点难度,在参考示例代码和问同学的情况下,解除了很多的疑惑。