杨玲201771010133《面向对象程序设计(java)》第十七周学习总结

coding

面向对象程序设计(java)》第十七周学习总结

第一部分:实验部分

实验名称:实验十七  线程同步控制

1、实验目的与要求

(1) 掌握线程同步的概念及实现技术;

(2) 线程综合编程练习

2、实验内容和步骤

实验1:测试程序并进行代码注释。

测试程序1:

l  在Elipse环境下调试教材651页程序14-7,结合程序运行结果理解程序;

l  掌握利用锁对象和条件对象实现的多线程同步技术。

 1package synch;

2

3import java.util.*;

4import java.util.concurrent.locks.*;

5

6/**

7 * A bank with a number of bank accounts that uses locks for serializing access.

8 * @version 1.30 2004-08-01

9 * @author Cay Horstmann

10*/

11publicclass Bank

12{

13privatefinaldouble[] accounts;//银行运转的基本数据

14private Lock bankLock;//锁对象

15private Condition sufficientFunds;//

16

17/**

18 * Constructs the bank.

19 * @param n the number of accounts

20 * @param initialBalance the initial balance for each account

21*/

22public Bank(int n, double initialBalance)

23 {

24 accounts = newdouble[n];

25 Arrays.fill(accounts, initialBalance);

26 bankLock = new ReentrantLock();

27 sufficientFunds = bankLock.newCondition();

28 }

29

30/**

31 * Transfers money from one account to another.

32 * @param from the account to transfer from

33 * @param to the account to transfer to

34 * @param amount the amount to transfer

35*/

36publicvoid transfer(int from, int to, double amount) throws InterruptedException

37 {

38 bankLock.lock();

39try

40 {//锁对象的引用条件对象

41while (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.signal();

49 }

50finally

51 {

52 bankLock.unlock();

53 }

54 }

55

56/**

57 * Gets the sum of all account balances.

58 * @return the total balance

59*/

60publicdouble getTotalBalance()

61 {

62 bankLock.lock();//加锁

63try

64 {

65double sum = 0;

66

67for (double a : accounts)

68 sum += a;

69

70return sum;

71 }

72finally

73 {

74 bankLock.unlock();//解锁

75 }

76 }

77

78/**

79 * Gets the number of accounts in the bank.

80 * @return the number of accounts

81*/

82publicint size()

83 {

84return accounts.length;

85 }

86 }

 1package 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*/

8publicclass SynchBankTest

9{

10publicstaticfinalint NACCOUNTS = 100;

11publicstaticfinaldouble INITIAL_BALANCE = 1000;

12publicstaticfinaldouble MAX_AMOUNT = 1000;

13publicstaticfinalint DELAY = 10;

14

15publicstaticvoid main(String[] args)

16 {

17 Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);

18for (int i = 0; i < NACCOUNTS; i++)

19 {

20int fromAccount = i;

21 Runnable r = () -> {

22try

23 {

24while (true)

25 {

26int toAccount = (int) (bank.size() * Math.random());

27double amount = MAX_AMOUNT * Math.random();

28 bank.transfer(fromAccount, toAccount, amount);

29 Thread.sleep((int) (DELAY * Math.random()));

30 }

31 }

32catch (InterruptedException e)

33 {

34 }

35 };

36 Thread t = new Thread(r);

37 t.start();

38 }

39 }

40 }

 运行结果如下:

测试程序2:

l  在Elipse环境下调试教材655页程序14-8,结合程序运行结果理解程序;

l  掌握synchronized在多线程同步中的应用。

 1package synch2;

2

3import 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*/

10publicclass Bank

11{

12privatefinaldouble[] accounts;

13

14/**

15 * Constructs the bank.

16 * @param n the number of accounts

17 * @param initialBalance the initial balance for each account

18*/

19public Bank(int n, double initialBalance)

20 {

21 accounts = newdouble[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*/

31publicsynchronizedvoid transfer(int from, int to, double amount) throws InterruptedException

32 {

33while (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();//解除那些在该对象上调用wait方法的线程阻塞状态。该方法只能在同步方法或同步块内部调用。

41 }

42

43/**

44 * Gets the sum of all account balances.

45 * @return the total balance

46*/

47publicsynchronizeddouble getTotalBalance()

48 {

49double sum = 0;

50

51for (double a : accounts)

52 sum += a;

53

54return sum;

55 }

56

57/**

58 * Gets the number of accounts in the bank.

59 * @return the number of accounts

60*/

61publicint size()

62 {

63return accounts.length;

64 }

65 }

 1package 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*/

9publicclass SynchBankTest2

10{

11publicstaticfinalint NACCOUNTS = 100;

12publicstaticfinaldouble INITIAL_BALANCE = 1000;

13publicstaticfinaldouble MAX_AMOUNT = 1000;

14publicstaticfinalint DELAY = 10;

15

16publicstaticvoid main(String[] args)

17 {

18 Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);

19for (int i = 0; i < NACCOUNTS; i++)

20 {

21int fromAccount = i;

22 Runnable r = () -> {

23try

24 {

25while (true)

26 {

27int toAccount = (int) (bank.size() * Math.random());

28double amount = MAX_AMOUNT * Math.random();

29 bank.transfer(fromAccount, toAccount, amount);

30 Thread.sleep((int) (DELAY * Math.random()));

31 }

32 }

33catch (InterruptedException e)

34 {

35 }

36 };

37 Thread t = new Thread(r);

38 t.start();

39 }

40 }

41 }

 运行结果如下:

y

测试程序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();

  }

}

 1class Cbank

2{

3privatestaticint s=2000;

4synchronizedpublicstaticvoid sub(int m)

5 {

6int temp=s;

7 temp=temp-m;

8try {

9 Thread.sleep((int)(1000*Math.random()));

10 }

11catch (InterruptedException e) { }

12 s=temp;

13 System.out.println("s="+s);

14 }

15 }

16

17

18class Customer extends Thread

19{

20

21publicvoid run()

22 {

23for( int i=1; i<=4; i++)

24 Cbank.sub(100);

25 }

26 }

27publicclass Thread3

28{

29publicstaticvoid 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张票

 

 1publicclass Demo {

2publicstaticvoid main(String[] args) {

3 Mythread mythread = new Mythread();

4 Thread t1 = new Thread(mythread);

5 Thread t2 = new Thread(mythread);

6 Thread t3 = new Thread(mythread);

7 t1.start();

8 t2.start();

9 t3.start();

10 }

11 }

12

13class Mythread implements Runnable {

14int t = 1;

15boolean flag = true;

16

17 @Override

18publicvoid run() {

19// TODO Auto-generated method stub

20while (flag) {

21try {

22 Thread.sleep(500);

23 } catch (Exception e) {

24// TODO: handle exception

25 e.printStackTrace();

26 }

27

28synchronized (this) {

29if (t <= 10) {

30 System.out.println(Thread.currentThread().getName() + "窗口售:第" + t + "张票");

31 t++;

32 }

33if (t > 10) {

34 flag = false;

35 }

36 }

37

38 }

39 }

40 }

运行结果如下:

4. 实验总结:

  通过本学期的实验课程学习,真的学到了很多,尤其是在老师和助教学长的耐心指导下,从最开始JDK的安装到后来自己能写出可以运行的程序,很开心。

以上是 杨玲201771010133《面向对象程序设计(java)》第十七周学习总结 的全部内容, 来源链接: utcz.com/z/508800.html

回到顶部