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

wy-201771010125 wy-201771010125     2023-02-11     553

关键词:

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

一 理论知识

1.多线程:多线程是进程执行过程中产生的多条执行线索。

2.进程: 线程是比进程执行更小的单位。线程不能独立存在,必须存在于进程中,同一进程的各线程间共享进程空间的数据。每个线程有它自身的产生、存在和消亡的过程, 是一个动态的概念。

3.线程创建、销毁和切换的负荷远小于进程,又称 为轻量级进程(lightweight process)。

4.Java实现多线程
    -创建Thread类的子类
    -在程序中定义实现Runnable接口的类

5.用Thread类的子类创建线程
    首先需从Thread类派生出一个子类,在该子类中 重写run()方法。
    class hand extends Thread public void run() ……
    然后用创建该子类的对象
    Lefthand left=new Lefthand();
    Righthand right=new Righthand();
    最后用start()方法启动线程
        left.start();
        right.start();

6.用Runnable()接口实现线程
    首先设计一个实现Runnable接口的类;
    然后在类中根据需要重写run方法;
    再创建该类对象,以此对象为参数建立Thread 类的对象;
    调用Thread类对象的start方法启动线程,将 CPU执行权转交到run方法。

7.线程的终止:调用interrupt()方法。

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

9.在Java中解决多线程同步问题的方法有两种: - Java SE 5.0中引入ReentrantLock类。 - 在共享内存的类方法前加synchronized修饰符。

二、实验部分

实验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 = 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;
   
技术分享图片
技术分享图片
/**
 * 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在多线程同步中的应用。

 

 

技术分享图片
/**
 * 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 = 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();//线程处于可运行状态
      
   
技术分享图片
技术分享图片
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 = 0;

      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 尝试解决程序中存在问题。

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=2000;//当类加载时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();//把变量customer1的值设置为分配给新的Customer对象的内部地址
   Customer customer2 = new Customer();
   customer1.start();
   customer2.start();
  
技术分享图片

 

 技术分享图片

修改后的代码:

 

技术分享图片
class Cbank



     private static int s=2000;

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

  

技术分享图片

 

技术分享图片

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

 

技术分享图片

三 实验总结

  本周实验学习了线程的同步,对线程有了更能进一步的学习,最后的编程的练习题通过学长的讲解以及演示,代码语句的解释,深入了解线程同步问题;本周也是最后一周的实验。

 
 














201771010125王瑜《面向对象程序设计(java)》第四周学习总结

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

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

                                 &n 查看详情

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

                                 &n 查看详情

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

                             实验九  异常.断言与日志第一部分:理论部分一:(1)异常:在程序的执行过程中所发生的异常事件,它中断指令的正常执行。常见的几种错误:A... 查看详情

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

实验六接口的定义与使用 一、理论部分该章学习的主要内容便有接口,回调,对象克隆,lambda表达式,内部类以及代理1、接口:(1)Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个接口(2)在Java程... 查看详情

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

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

08-面向对象----j

一面向对象的程序设计的由来请参考:http://www.cnblogs.com/linhaifeng/articles/6428835.html二什么是面向对象的程序设计及为什么要有它面向过程的程序设计的核心是过程,过程即解决问题的步骤,面向过程的设计就好比精心设计好一条... 查看详情

2020面向对象设计与构造第三单元博客总结(代码片段)

面向对象设计与构造第三单元总结一、JML规格化设计JML,全称TheJavaModelingLanguage,是用于对Java程序进行规格化描述的注释性质语言。笔者在本文总结了常见的JML语法描述。1.注释结构在注释行或注释块中,以@开头的行被认作JML注... 查看详情

面向对象

老王和隔壁的美女猜数字,一共有四次机会,猜到了就有特殊奖励publicclasstest{publicstaticvoidmain(String[]args){inti=(int)(Math.random()*10);Scannerinput=newScanner(System.in);for(intj=0;j<4;j++){System.out.println("老王第"+(j+1)+"次 查看详情

201771010126王燕《面向对象程序设计(java)》第二周学习总结

201771010126王燕《面向对象程序设计(java)》第二周学习总结一.理论知识学习部分3.1j简单的java应用程序标识符由字母、下划线、美元符号和数字组成,且第一个符号不能为数字。标识符可用作:类名、变量名、方法名、数组名... 查看详情

201823072019-2020-1《数据结构与面向对象程序设计》实验1报告

课程:《程序设计与数据结构》班级:1823姓名:王美皓学号:20182322实验教师:王美皓实验日期:2019年9月9日必修/选修:必修1.实验内容基于命令行和IDE(IntelljIDEA简易教程](http://www.cnblogs.com/rocedu/p/4421202.html)进行简单的Java程... 查看详情

杨其菊201771010134《面向对象程序设计(java)》第三周学习总结(代码片段)

  《面向对象程序设计(Java)》第三周学习总结第一部分:理论知识 这周课程没有新进度,由于感觉对基础语法的不熟悉,复习了一遍前三章的细碎知识,学到一些之前不知道的原理: 1.计算机高级语言按程序的... 查看详情

c++面向对象的主要体现是啥?

...得对我有用的话,我会再追加分。)C++面向对象是表现在程序设计的过程上,它是突破了C的结构化设计而出现的完全以实际问题为入手点的。C++的面向对象3个特性:1.封装。2.继承。3.多态。尤其重要的是,它采用类的设计,杜... 查看详情

徐思201771010132《面向对象程序设计(java)》第十二周学习总结(代码片段)

一、理论知识部分Java的抽象窗口工具箱(AbstractWindowToolkit,AWT)包含在java.awt包中,它提供了许多用来设计GUI的组件类和容器类。大部分AWT组件都有其Swing的等价组件,Swing组件的名字一般是在AWT组件名前面添加一个字母“J”。通... 查看详情

201771010110孔维滢《面向对象程序设计(java)》第十二周学习总结

理论知识部分1.Java的抽象窗口工具箱(AbstractWindowToolkit,AWT)包含在java.awt包中,它提供了许多用来设计GUI的组件类和容器类。2.Swing用户界面库是非基于对等体的GUI工具箱。Swing类库被放在javax.swing包里。3.大部分AWT组件都有其Swing... 查看详情

马凯军201771010116《面向对象与程序设计java》第十二周学习总结(代码片段)

一、理论与知识学习部分Java的抽象窗口工具箱(AbstractWindowToolkit,AWT)包含在java.awt包中,它提供了许多用来设计GUI的组件类和容器类。大部分AWT组件都有其Swing的等价组件,Swing组件的名字一般是在AWT组件名前面添加一个字母“J... 查看详情

201771010134杨其菊《面向对象程序设计java》第十二周学习总结(代码片段)

...bsp; 内容概要: AWT与Swing简介;框架的创建;图形程序设计; 显示图像;1.AWT组件:2.Swing组件层次关系3.AWT与Swing的关系:大部分AWT组件都有其Swing的等价组件; Swing组件的名字一般是在AWT组件名前面添加一个字母“J 查看详情

面向对象程序设计介绍以及面向对象的基本特征

  面向对象的程序设计(ObjectOrientedProgramming,OOP)方法是目前比较流行的程序设计方法,和面向过程的程序设计比,它更符合人类的自然思维方式。在面向过程程序设计中,程序=数据+算法,数据和对数据的操作是分离的,如... 查看详情