201771010111李瑞红《第十七周学习总结》(代码片段)

lrhlrh123---- lrhlrh123----     2023-02-10     365

关键词:

实验十七  线程同步控制

实验时间 2018-12-10

一、理论部分

1.Java通过多线程的并发运行提高系统资源利用 率,改善系统性能。

2.假设有两个或两个以上的线程共享 某个对象,每个线程都调用了改变该对象类状态的方法,就会引起的不确定性。

3.多线程并发执行中的问题

    多个线程相对执行的顺序是不确定的。线程执行顺序的不确定性会产生执行结果的不确定性。在多线程对共享数据操作时常常会产生这种不确定性。

4.多线程并发运行不确定性问题解决方案:引入线程同步机制。

5、线程的同步

-多线程并发运行不确定性问题解决方案:引入线程同步机制,使得另一线程要使用该方法,就只能等待。

- 在Java中解决多线程同步问题的方法有两种:

- Java SE 5.0中引入ReentrantLock类

- 在共享内存的类方法前加synchronized修饰符。

……

public synchronized static void sub(int m)

……

(1)解决方案一:锁对象与条件对象

用ReentrantLock保护代码块的基本结构如下:

myLock.lock();

try

     critical section

finally

     myLock.unlock(); 

有关锁对象和条件对象的关键要点:

? 锁用来保护代码片段,保证任何时刻只能有一个线程执行被保护的代码。

锁管理试图进入被保护代码段的线程。

? 锁可拥有一个或多个相关条件对象。
每个条件对象管理那些已经进入被保护的代码段但还不能运行的线程。

(2)解决方案二: synchronized关键字

synchronized关键字作用:

?某个类内方法用synchronized 修饰后,该方法被称为同步方法;
?只要某个线程正在访问同步方法,其他线程欲要访问同步方法就被阻塞,直至线程从同步方法返回前唤醒被阻塞线程,其他线程方可能进入同步方法。

3、在同步方法中使用wait()、notify 和notifyAll()方法

? 一个线程在使用的同步方法中时,可能根据问题的需要,必须使用wait()方法使本线程等待,暂时让出CPU的使用权,并允许其它线程使用这个同步方法。

? 线程如果用完同步方法,应当执行notifyAll()方法通知所有由于使用这个同步方法而处于等待的线程结束等待。

二、实验部分

1、实验目的与要求

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

(2) 线程综合编程练习

2、实验内容和步骤

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

测试程序1:

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

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

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();
   

   /**
    * 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.signal();
      
      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;
   
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();
      
   

技术分享图片

测试程序2:

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

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

package synch2;

import java.util.*;

/**
 * 使用同步原语的具有多个银行帐户的银行
 * @version 1.30 2004-08-01
 * @author Cay Horstmann
 */
public class Bank

   private final double[] accounts;

   /**
    * 构建了银行。
    * @param  账户数量
    * @param 每个账户的初始余额
    */
   public Bank(int n, double initialBalance)
   
      accounts = new double[n];
      Arrays.fill(accounts, initialBalance);
   

   /**
    * 把钱从一个账户转到另一个账户。
    * @param 从账户转出
    * @param 到账转到
    * @param 转帐金额
    */
   public synchronized void transfer(int from, int to, double amount) throws InterruptedException
   
      while (accounts[from] < amount)
         wait();//Object类
      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();
   
   /**
    *获取所有帐户余额的总和。
    * @return 总平衡
    */
   public synchronized double getTotalBalance()
   
      double sum = 0;

      for (double a : accounts)
         sum += a;

      return sum;
   

   /**
    * 获取银行中的帐户编号。
    * @return 账户数量
    */
   public int size()
   
      return accounts.length;
   
package synch2;

/**
 * 这个程序展示了多线程如何安全地访问一个数据结构,使用同步方法。
 * @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();
      
   

技术分享图片

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

 

源程序运行结果

技术分享图片

存在的问题是运行顺序混乱,修改以后的程序

import javax.sql.rowset.spi.SyncFactory;
class Cbank


     private static int s=2000;
     public synchronized static void sub1(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.sub1(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张票,程序输出结果类似(程序输出不唯一,可以是其他类似结果)。

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

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;
                
            
        
    

技术分享图片

实验总结:本周学习内容较少,理解起来也比较容易,学习了同步线程的相关问题,了解了并发多线程的两种解决方法,一种是锁对象,还有一种是synchronized关键字。很感谢学长一学期的帮助,这周学长演示的东西基本都理解了。

 

 

技术分享图片






201771010111李瑞红《第十二周学习总结》(代码片段)

实验十二 图形程序设计实验时间2018-11-14第一部分:理论知识总结1.Java的抽象口工具箱(AbstractWindowToolkit,AWT)包含在java.awt包中,它提供了许多用来设计GUI的组件类和容器类。2.AWT库处理用户界面元素的方法:把图形元素的创... 查看详情

201771010111李瑞红《第十一周学习总结》(代码片段)

  实验十一  集合实验时间2018-11-8第一部分:理论总结1.栈(Stack)也是一种特殊的线性表,是一种后进先出(LIFO)的结构。栈是限定仅在表尾进行插入和删除运算的线性表,表尾称为栈顶(top),表头称为(bottom)。栈的物... 查看详情

201771010111李瑞红《第十八周学习总结》(代码片段)

1、实验目的与要求(1) 综合掌握java基本程序结构;(2) 综合掌握java面向对象程序设计特点;(3) 综合掌握javaGUI 程序设计结构;(4) 综合掌握java多线程编程模型;(5)综合编程练习。2、实验内容和步骤任务1:填写... 查看详情

李瑞红201771010111《面向对象程序设计(java)》第一周学习总结

李瑞红201771010111《面向对象程序设计(java)》第一周学习总结第一部分:课程准备部分填写课程学习平台注册账号,平台名称注册账号博客园:www.cnblogs.com3451487460程序设计评测:https://pintia.cn/[email protected]代码托管平台:htt... 查看详情

李瑞红201771010111《第九周学习总结》(代码片段)

实验九异常、断言与日志实验时间2018-10-25第一部分:理论部分 1.异常:在程序的执行过程中所发生的异常事件,它中断指令的正常执行。Java的异常处理机制可以控制程序从错误产生的位置转移到能够进行错误处理的位置。&nbs... 查看详情

李瑞红201771010111《面向对象程序设计(java)》第四周学习总结

 实验四:类与对象的定义及使用第一部分:理论知识学习1.类与对象概念 (1)类是构造对象的模板或蓝图,由类构造对象的过程称为创建类的实例。 (2)对象:即数据,对象有三个特性,行为、状态、标识。2.类与对象的... 查看详情

李瑞红201771010111第二周实验总结报告

第一部分:理论知识学习本章主要内容是java的基本程序设计结构,包括以下几个方面的知识,(1)标识符、关键字、注释的相关知识;(2)数据类型;(3)变量;(4)运算符;(5)类型转换;(6)字符串;(7)输入输出;(8))控制流程;(9)大数... 查看详情

2017710101111李瑞红《第七周学习总结》(代码片段)

实验七继承附加实验实验时间2018-10-11第一部分:理论部分  1.继承:如果两个类存在继承关系,则子类会自动继承父类的方法和变量,在子类中可以调用父类的方法和变量,如果想要在子类里面做一系列事情,应该放在父类无... 查看详情

李瑞红201771010111(代码片段)

实验六继承定义与使用实验时间2018-9-2第一部分:理论知识第五章1.类、超类和子类5.2Object:所有类的超类5.3泛型数组列表5.4对象包装器和自动打包5.5参数数量可变的方法5.6枚举类5.7继承设计的技巧5.1类、超类和子类5.2Object:所... 查看详情

第十七周学习进度条

 第十七周所花时间(包括上课)约7小时代码量(行)100行左右博客量(篇)2了解到的知识点这周主要复习,准备期末的考试复习了以前学过的知识点新的知识基本没有接触 查看详情

201771010108-韩腊梅-第十七周学习总结(代码片段)

第十七周学习总结 一、知识总结1.创建线程的2种方法方式1:继承java.lang.Thread类,并覆盖run()方法。优势:编写简单;劣势:无法继承其他父类方式2:实现java.lang.Runnable接口,并实现run()方法。优势:可以继承其他类,多线... 查看详情

201771010125王瑜《面向对象程序设计(java)》第十七周学习总结(代码片段)

...     201771010125王瑜《面向对象程序设计(java)》第十七周学习总结一理论知识1.多线程:多线程是进程执行过程中产生的多条执行线索。2.进程:线程是比进程执行更小的单位。线程不能独立存在,必须存在于进程中,同... 查看详情

张云飞201771010143《面对对象程序设计(java)》第十七周学习总结

1、实验目的与要求(1) 掌握线程同步的概念及实现技术; (2) 线程综合编程练习2、实验内容和步骤实验1:测试程序并进行代码注释。测试程序1:l 在Elipse环境下调试教材651页程序14-7,结合程序运行结果理解程序;... 查看详情

201871010111-刘佳华《面向对象程序设计(java)》第十七周学习总结(代码片段)

201871010111-刘佳华《面向对象程序设计(java)》第十七周学习总结实验十七 线程同步控制实验时间2019-12-20第一部分:理论知识总结16.Java的线程调度采用优先级策略:  优先级高的先执行,优先级低的后执行;  ... 查看详情

2016710101302016-2017-2《java程序设计》第十七周学习小结

线程学习总结:线程是单个的执行流程序一和程序二的区别在于:当程序一已经有动作时,会对用户的操作排入队列,不能同时运行两个动作,程序二则可以也就是实现了程序的并发性。新建线程有两个方法:1.用接口实现。2.... 查看详情

常惠琢201771010102《面向对象程序设计(java)》第十七周学习总结(代码片段)

实验十七  线程同步控制实验时间 2018-12-101、实验目的与要求(1) 掌握线程同步的概念及实现技术; (2) 线程综合编程练习2、实验内容和步骤实验1:测试程序并进行代码注释。测试程序1:l 在Elipse环境下... 查看详情

201771010137赵栋《面向对象程序设计(java)》第十七周学习总结(代码片段)

 (1)综合掌握java基本程序结构;(2) 综合掌握java面向对象程序设计特点;(3)综合掌握javaGUI 程序设计结构;(4)综合掌握java多线程编程模型;(5)综合编程练习。2、实验内容和步骤任务1:填写课程课后调查问卷,网址:htt... 查看详情

第十七周学习(代码片段)

1.图的定义图(Graph)是由顶点(vertex)的有穷非空集合和顶点之间边(edge)的集合组成,通常表示为:G(V,E),其中,G表示一个图,V是图G中顶点的集合,E是图G中边的集合a.若顶点之间Vi和Vj之间没有方向,则为无向边,用无序偶对(Vi,Vj)... 查看详情