zoukankan      html  css  js  c++  java
  • 201871010104-陈园园《面向对象程序设计(java)》第十七周学习总结

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

     

    项目 内容
    这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/
    这个作业要求在哪里 https://www.cnblogs.com/lily-2018/p/11441372.html
    作业学习目标

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

    (2) 线程综合编程练习

    第一部分:总结理论知识

    多线程调度
         java提供一个线程调度器来监控程序启动后进入可运行状态的所有线程。线程调度器按照线程的优先级决定应调度那些线程来执行。处于可运行状态的线程首先进入就绪队列排队等候CPU资源,同一时刻在就绪队列中的线程可能有多个。java的多线程系统会给每个线程自动分配一个优先级。

    java的线程调度采用优先级的策略:

    1)优先级高的先执行,优先级低的后执行。

    2)多线程系统会自动为每个线程分配一个人优先级,缺省时,继承其父类的优先级。

    3)任务紧急的线程,其优先级较高。

    4)同优先级的线程按“先进先出”的队列原则。

    Thread类有三个与线程优先级有关的静态量:

    MAX_PRIORITY:最大优先权,值为10;

    MIN_PRIORITY:最小优先权,值为1;

    NORM_PRIORITY:默认优先权,值为5。

    调用setPrioritya(int a)重置当前线程的优先级,a取值可以是前述的三个静态量。

    调用getPriority()获得当前线程优先级。

    下面几种情况下,当前运行线程会放弃CPU:

    -线程调用了yield()或s条件变量,以及线程调用sleep()方法;

    -抢先式系统下,有高优先级的线程参与调度;

    -由于当前线程进行I/O访问、外存读写、等待用户输入等操作导致线程阻塞;或者是为等候一个wait()方法。

    守护线程

    守护线程是唯一用途是为其他线程提供服务。例如计时线程。

    若JVM的运行任务只剩下守护线程时,JVM就退出了。

    在一个线程启动之前,调用setaDaemon方法可将线程转换为守护线程(daemon thread)。

    例如:setDaemon(true);

    用setPrority()方法可以改变线程的优先级。

    多线程并发存在问题:

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

    存在问题:假设有两个或两个以上的线程共享某个对象,每个线程都调用了改变该对象类状态的方法,会产生什么结果呢?参照实验测试程序三。

    多线程并发执行中的问题:

    1)多个线程的相对执行顺序不确定。

    2)线程执行顺序不确定性会产生执行结果的不确定性。

    3)在多线程对共享数据操作时常常会产生不确定性。

    线程的同步

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

    在java中多线程同步方法有两种:

    -javaSE5.0中引入ReentrantLock类。

    -在共享内存中类方法前加synchronized修饰符。public synchronized static void sub(int m)

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

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

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

    可拥有一个或多个相关条件对象

    每个条件对象管理那些已经进入被保护的代码段但还不能运行的线程。

    在临界区中使用条件对象的await()、signal()、signalAll()方法实现线程之间的交互。

    第二部分:实验测试

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

    测试程序1:

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

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

    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();//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.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;
       }
    }
    
    bank
    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();
          }
       }
    }
    
    SynchBank

    运行结果:

    测试程序2:

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

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

     

    package synch2;
    
    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();//解除那些在该对象上调用wait方法的线程的阻塞状态
       }
    
       /**
        * 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;
       }
    }
    
    Bank

     

    package synch2;
    
    /**
     * 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();
          }
       }
    }
    
    SynchBankTest2

    运行结果:

    测试程序3:

    1)在Elipse环境下运行以下程序,结合程序运行结果分析程序存在问题;

    2)尝试解决程序中存在问题。

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

    运行结果:

     修改程序如下:

    package test2;
    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张票,程序输出结果类似(程序输出不唯一,可以是其他类似结果)。

    代码如下:

    package synch3;
    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;
                    }
                }
            }
        }
     
    }

    运行结果:

     结对照片

    实验总结:

         本节课继续学习了线程同步技术以及上锁问题,在上节课的基础上更一步加强了对线程的了解。在测试程序中更深一步的理解了理论知识,发现了线程的多变性,希望在接下来的学习中可以更好的运用。继续加油吧!结对编程的过程中,遇到的问题通过一起商量得到了解决 ,也学到了很多知识。

     

     

      

  • 相关阅读:
    【WIN10】我的第一個WIN10-UWP應用——古文觀止
    【WIN10】文本圖標
    【WIN10】VisualStateManager使用說明
    【WIN10】Storyboard動畫板
    【WIN10】Bind、Binding與Converter的使用
    struts执行过程
    在jsp中的局部和全局变量
    jsp页面中的:<%@ page contentType="text/html; charset=utf-8" language="java"%>的作用及含义
    jsp中的this
    在Java接口中怎样访问定义的常量呢?
  • 原文地址:https://www.cnblogs.com/chanyeol1127/p/12072414.html
Copyright © 2011-2022 走看看