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

    项目

    内容

    这个作业属于哪个课程

    https://www.cnblogs.com/nwnu-daizh/

    这个作业的要求在哪里

    https://www.cnblogs.com/nwnu-daizh/p/11435127.html

    作业学习目标

    1) 理解和掌握线程的优先级属性及调度方法;

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

    (3) Java线程综合编程练习

    第一部分:总结线程同步技术

    当我们使用多个线程访问同一资源的时候,且多个线程中对资源有写的操作,就容易出现线程安全问题。
    要解决上述多线程并发访问一个资源的安全性问题:也就是解决重复票与不存在票问题,Java中提供了同步机制
    (synchronized)来解决。
    根据案例简述:

    窗口1线程进入操作的时候,窗口2和窗口3线程只能在外等着,窗口1操作结束,窗口1和窗口2和窗口3才有机会进入代码
    去执行。也就是说在某个线程修改共享资源的时候,其他线程不能修改该资源,等待修改完毕同步之后,才能去抢夺CPU
    资源,完成对应的操作,保证了数据的同步性,解决了线程不安全的现象。

    有三种方式完成同步操作:

    1. 同步代码块。
    2. 同步方法。
    3. 锁机制。

    同步代码块:

    synchronized 关键字可以用于方法中的某个区块中,表示只对这个区块的资源实行互斥访问。
    格式:
    同步锁:
    对象的同步锁只是一个概念,可以想象为在对象上标记了一个锁.
    1. 锁对象 可以是任意类型。
    2. 多个线程对象 要使用同一把锁。
    注意:在任何时候,最多允许一个线程拥有同步锁,谁拿到锁就进入代码块,其他的线程只能在外等着
    (BLOCKED)。

    public class Ticket implements Runnable{
    private int ticket = 100;
    Object lock = new Object();
    /*
    * 执行卖票操作
    */
    @Override
    public void run() {
    //每个窗口卖票的操作
    //窗口 永远开启
    while(true){
    synchronized (lock) {
    if(ticket>0){//有票 可以卖
    //出票操作
    //使用sleep模拟一下出票时间
    try {
    Thread.sleep(50);
    } catch (InterruptedException e) {
    // TODO Auto‐generated catch block
    e.printStackTrace();
    }
    //获取当前线程对象的名字
    String name = Thread.currentThread().getName();
    System.out.println(name+"正在卖:"+ticket‐‐);
    }
    }
    }

    同步方法:使用synchronized修饰的方法,就叫做同步方法,保证A线程执行该方法的时候,其他线程只能在方法外
    等着。
    格式:
    同步锁是谁?
    对于非static方法,同步锁就是this。
    对于static方法,我们使用当前方法所在类的字节码对象(类名.class)。

    public class Ticket implements Runnable{
    private int ticket = 100;
    /*
    * 执行卖票操作
    */
    @Override
    public void run() {
    //每个窗口卖票的操作
    //窗口 永远开启
    while(true){
    sellTicket();
    }
    }
    /*
    * 锁对象 是 谁调用这个方法 就是谁
    * 隐含 锁对象 就是 this
    *
    */
    public synchronized void sellTicket(){
    if(ticket>0){//有票 可以卖
    //出票操作
    //使用sleep模拟一下出票时间
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    // TODO Auto‐generated catch block
    e.printStackTrace();

    Lock锁
    java.util.concurrent.locks.Lock 机制提供了比synchronized代码块和synchronized方法更广泛的锁定操作,
    同步代码块/同步方法具有的功能Lock都有,除此之外更强大,更体现面向对象。
    Lock锁也称同步锁,加锁与释放锁方法化了,如下:
    public void lock() :加同步锁。
    public void unlock() :释放同步锁。

    public class Ticket implements Runnable{
    private int ticket = 100;
    Lock lock = new ReentrantLock();
    /*
    * 执行卖票操作
    */
    @Override
    public void run() {
    //每个窗口卖票的操作
    //窗口 永远开启
    while(true){
    lock.lock();
    if(ticket>0){//有票 可以卖
    //出票操作
    //使用sleep模拟一下出票时间
    try {
    Thread.sleep(50);
    } catch (InterruptedException e) {
    // TODO Auto‐generated catch block
    e.printStackTrace();
    }
    //获取当前线程对象的名字
    String name = Thread.currentThread().getName();
    System.out.println(name+"正在卖:"+ticket‐‐);
    }
    lock.unlock();
    }
    }
    }

    第二部分:实验部分

    1、实验目的与要求

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

    (2) 线程综合编程练习

    2、实验内容和步骤

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

    测试程序1:

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

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

    package 线程;
    
    /**
     * 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类创建多线程
             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);//实现Thread类
             t.start();
          }
       }
    }
    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)//创建构造方法bank
       {
          accounts = new double[n];
          Arrays.fill(accounts, initialBalance);
          bankLock = new ReentrantLock();//创建一个ReentrankLock对象,名为bankLock
          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;
       }
    }

    测试程序2:

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

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

    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();
          }
       }
    }
    package 线程;
    
    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)//创建构造方法bank
       {
          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
       //使用synchronsized修饰的方法,使其为同步方法
       {
          while (accounts[from] < amount)//判断账户余额是否少于要转账的金额
             wait();//如果是让该线程进入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()//synchronized所修饰的方法
       {
          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  尝试解决程序中存在问题。

    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 线程;
    
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class Cbank {
        static Lock lock=new ReentrantLock();
        private static int s = 2000;
        
        public static  void sub(int m) {
              lock.lock();
            int temp = s;
            temp = temp - m;
            try {
                Thread.sleep((int) (1000 * Math.random()));
            } catch (InterruptedException e) {
            }
            s = temp;
            System.out.println("s=" + s);
            lock.unlock();
        }
        
    }
    package 图像程序设计;
    
    import 线程.Customer;
    
    public class Thread3 {
        public static void main(String[] args) {
    
            {
                Customer customer1 = new Customer();
                Customer customer2 = new Customer();
                customer1.start();
                customer2.start();
            }
        }
    }
    package 线程;
    
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class Customer extends Thread {
    //    Object lock = new Object();
    
    //    Lock lock=new ReentrantLock();
        public void run() {
            //synchronized (lock) {
                for (int i = 1; i <= 4; i++) {
                    Cbank cbank = new Cbank();
    
                    cbank.sub(100);
                //}
            }
        }
    }

    第二种:

    package border;
    
    class Cbank
    {
         private static int s=2000;
         public  static synchronized 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张票

    编程代码:

    package sy;
    
    public class Tickets {
    public static void main(String[] args) {
        Ticket ticket=new Ticket();
        Thread t1= new Thread(ticket,"Thread-0");
        Thread t2 = new Thread(ticket,"Thread-1");
        Thread t3 = new Thread(ticket,"Thread-2");
        t1.start();
        t2.start();
        t3.start();
    }
    }
    package sy;
    
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class Ticket implements Runnable {
        private int ticket =1;
        Lock lock = new ReentrantLock();
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                // 每个窗口永远开启
                lock.lock();
                if (ticket <=10) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 获得当前线程对象名字
                    String name = Thread.currentThread().getName();
                    System.out.println(name + "窗口售:第" + ticket+++"张票");
                }
                lock.unlock();
    
            }
        }
    }

     

    第三部分:实验总结

    通过本次实验我对线程的理解得以加深,并且学习到了线程常见问题的解决方法,在今后我会继续努力。

  • 相关阅读:
    Selenium3+python3自动化(十六)--单选框和复选框(radiobox、checkbox)
    Selenium3+python3自动化(十五)--JS处理滚动条,window.scrollTo(xpos,ypos)
    Selenium3+python3自动化(十四)--alertsconfirmprompt
    Selenium3+python3自动化(十三)--select下拉框
    Selenium3+python3自动化(十二)--iframe
    UPC-5627 Boxes(思维)
    UPC-5007 High Score(计算)
    UPC-5003 Dunglish(模拟)
    Hrbust-1830 第一个重复出现的数(线段树区间最值查询)
    UPC-5599 Minimum Sum(线段树求区间最小值+二分区间计数)
  • 原文地址:https://www.cnblogs.com/1763088787h/p/12088498.html
Copyright © 2011-2022 走看看