201871010128-杨丽霞《面向对象程序设计(java)》第十七周学习总结

时间:2019-12-23
本文章向大家介绍201871010128-杨丽霞《面向对象程序设计(java)》第十七周学习总结,主要包括201871010128-杨丽霞《面向对象程序设计(java)》第十七周学习总结使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

201871010128-杨丽霞《面向对象程序设计(java)》第十七周学习总结

项目

内容

这个作业属于哪个课程

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

这个作业的要求在哪里

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

作业学习目标

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

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

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

 

随笔博文正文内容包括:

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

一、 Java线程调度与优先级

Java提供一个线程调度器来监视和控制Runnable状态的线程。线程的调度策略采用抢占式,优先级高的线程比优先级低的线程优先执行。在优先级相同的情况下,按照“先到先服务”的原则。

每个Java程序都有一个默认的主线程,就是通过JVM启动的第一个线程。对于应用程序,主线程执行的是main()方法。对于Applet主线程是指浏览器加载并执行小应用程序的那一个线程。

子线程是由应用程序创建的线程。

还有一种线程称为守护现成(Daemon),这是一种用于监视其他线程工作的服务线程,优先级为最低。

二、线程同步:

1、使用synchronized关键字 由于java的每个对象都有一个内置锁,当用此关键字修饰方法时, 内置锁会保护整个方法。在调用该方法前,需要获得内置锁,否则就处于阻塞状态。

注: synchronized关键字也可以修饰静态方法,此时如果调用该静态方法,将会锁住整个类。同步是一种高开销的操作,因此应该尽量减少同步的内容。通常没有必要同步整个方法,使用synchronized代码块同步关键代码即可。

同步方法:给一个方法增加synchronized修饰符之后就可以使它成为同步方法,这个方法可以是静态方法和非静态方法,但是不能是抽象类的抽象方法,也不能是接口中的接口方法。

2、wait和notify

wait():使一个线程处于等待状态,并且释放所持有的对象的lock。

sleep():使一个正在运行的线程处于睡眠状态,是一个静态方法,调用此方法要捕捉InterruptedException异常。

notify():唤醒一个处于等待状态的线程,注意的是在调用此方法的时候,并不能确切的唤醒某一个等待状态的线程,而是由JVM确定唤醒哪个线程,而且不是按优先级。

3、Allnotity():唤醒所有处入等待状态的线程,注意并不是给所有唤醒线程一个对象的锁,而是让它们竞争。

使用特殊域变量volatile实现线程同步

a.volatile关键字为域变量的访问提供了一种免锁机制

    b.使用volatile修饰域相当于告诉虚拟机该域可能会被其他线程更新

    c.因此每次使用该域就要重新计算,而不是使用寄存器中的值 

    d.volatile不会提供任何原子操作,它也不能用来修饰final类型的变量 

三、对象锁也叫方法锁,是针对一个对象实例的,它只在该对象的某个内存位置声明一个标识该对象是否拥有锁,所有它只会锁住当前的对象,而并不会对其他对象实例的锁产生任何影响,不同对象访问同一个被synchronized修饰的方法的时候不会阻塞 

创建一个类,synchronized修饰普通方法,即为对象锁,那么这个时候,多个线程访问同一个对象实例的这个方法时,是会同步的,并且只有一个线程执行完,另一个线程才会执行。

java的对象锁和类锁:java的对象锁和类锁在锁的概念上基本上和内置锁是一致的,但是,两个锁实际是有很大的区别的,对象锁是用于对象实例方法,或者一个对象实例上的,类锁是用于类的静态方法或者一个类的class对象上的。我们知道,类的对象实例可以有很多个,但是每个类只有一个class对象,所以不同对象实例的对象锁是互不干扰的,但是每个类只有一个类锁。但是有一点必须注意的是,其实类锁只是一个概念上的东西,并不是真实存在的,它只是用来帮助我们理解锁定实例方法和静态方法的区别的

第二部分:实验部分

实验1:测试程序1(5分)

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)            //Bank构造器,两个入口参数
   {
      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.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;
   }
}
 1 package 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  */
 8 public class SynchBankTest
 9 {   //常量的定义
10    public static final int NACCOUNTS = 100;
11    public static final double INITIAL_BALANCE = 1000;
12    public static final double MAX_AMOUNT = 1000;
13    public static final int DELAY = 10;
14     
15    public static void main(String[] args)
16    {
17       Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
18       for (int i = 0; i < NACCOUNTS; i++)
19       {
20          int fromAccount = i;
21          Runnable r = () -> {                //Runnable接口实现创建线程
22             try
23             {
24                while (true)
25                {
26                   int toAccount = (int) (bank.size() * Math.random());   //随机函数产生
27                   double amount = MAX_AMOUNT * Math.random();            //随机函数产生MAX_AMOUNT个随机数
28                   bank.transfer(fromAccount, toAccount, amount);         //调用transfer方法在同行之间进行转账
29                   Thread.sleep((int) (DELAY * Math.random()));           //随机睡眠时间DELAY
30                }
31             }
32             catch (InterruptedException e)
33             {
34             }            
35          };
36          Thread t = new Thread(r);  //创建一个线程
37          t.start();                 //该线程开始工作
38       }
39    }
40 }

运行截图:

实验1:测试程序2(5分)

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

l 掌握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();//在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待
      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;
   }
}
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 = () -> { //Runnable接口创建线程
            try
            {
               while (true)
               {
                  int toAccount = (int) (bank.size() * Math.random());      //随机函数
                  double amount = MAX_AMOUNT * Math.random();      //产生 1000个随机数
                  bank.transfer(fromAccount, toAccount, amount);   //transfer方法在同行之间进行转账
                  Thread.sleep((int) (DELAY * Math.random()));     //随机产生0-10毫秒之间的一个数,调用sleep方法睡眠。
               }
            }
            catch (InterruptedException e)
            {
            }
         };
         Thread t = new Thread(r);       //新建一个线程
         t.start();               //调用start方法开启线程
      }
   }
}

运行截图:

实验1:测试程序3(5分)

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

尝试解决程序中存在问题

 1 class Cbank
 2 {
 3      private static int s=2000;
 4      public   static void sub(int m)
 5      {
 6            int temp=s;
 7            temp=temp-m;
 8           try {
 9      Thread.sleep((int)(1000*Math.random()));
10    }
11            catch (InterruptedException e)  {              }
12           s=temp;
13           System.out.println("s="+s);
14   }
15 }
16  
17  
18 class Customer extends Thread
19 {
20   public void run()
21   {
22    for( int i=1; i<=4; i++)
23      Cbank.sub(100);
24     }
25  }
26 public class Thread3
27 {
28  public static void main(String args[])
29   {
30    Customer customer1 = new Customer();
31    Customer customer2 = new Customer();
32    customer1.start();
33    customer2.start();
34   }
35 }

运行截图:

修改后代码:

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:结对编程练习包含以下4部分(10分)

利用多线程及同步方法,编写一个程序模拟火车票售票系统,共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张票

1)   程序设计思路简述;

火车票售票系统,售票时窗口0、1、2一起工作,利用线程同步技术实现。

2)   符合编程规范的程序代码;

package Test

class Ticketsthread implements Runnable {
    public static final int DELAY = 1000;
    int t = 1;
    boolean flag = true;

    public void run() {
        while (flag) {
            try {
                Thread.sleep((int) (DELAY * Math.random()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (this) {
                if (t <= 10) {
                    System.out.println(Thread.currentThread().getName() + "窗口售:第" + t + "張票");
                    t++;
                }
                if (t > 10) {
                    flag = false;
                }
            }
        }

    }
}

public class TicketsTest {
    public static void main(String[] args) {
        Ticketsthread th = new Ticketsthread();
         new Thread(th).start();
         new Thread(th).start();
         new Thread(th).start();
        
    }
}

3)程序运行功能界面截图;


实验总结:(5分)

本周学习了线程技术,了解了多线程并发执行中的问题。多个线程相对执行的顺序是不确定的。线程执行顺序的不确定性会产生执行结果的不确定性。在多线程对共享数据操作时常常会产生这种不确定性。.多线程并发运行不确定性问题解决方案:引入线程同步机制。锁对象与条件对象:用ReentrantLock保护代码块、synchronized关键字、synchronized关键字作用:某个类内方法用synchronized 修饰后,该方 法被称为同步方法; 只要某个线程正在访问同步方法,其他线程 欲要访问同步方法就被阻塞,直至线程从同 步方法返回前唤醒被阻塞线程,其他线程方 可能进入同步方法。

原文地址:https://www.cnblogs.com/ylxzjh/p/12088397.html