201777010217-金云馨《面向对象程序设计(java)》第十七周学习总结

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

(1) 掌握菜单组件用途及常用API;

(2) 掌握对话框组件用途及常用API;

(3) 学习设计简单应用程序的GUI。

第一部分:知识总结

1.线程的同步:

  多线程并发运行不确定性问题解决方案:

  引入线程同步机制;

Java中线程同步方法有两种:

1JavaSE5.0中引入ReentrantLock类;

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

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

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

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

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

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

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

  一个线程在临界区时,可能根据问题的需要,必须使用锁对象的await()方法使本线程等待,暂时让出CPU的使用权,并允许其他线程使用这个同步方法;

  线程若退出临界区,应用signal()方法随机的选择一个线程解除其阻塞状态;

  线程若退出临界区,执行notifyAll()方法通知所有由于等待该临界区的线程结束等待。

第二部分:实验部分

 

实验1:测试程序1

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

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

实验代码如下:

package synch;
 
import java.util.*;
import java.util.concurrent.locks.*;
 
/**
一个银行有许多银行帐户,使用锁序列化访问 * @version 1.30 2004-08-01
 * @author Cay Horstmann
 */
public class Bank
{
   private final double[] accounts;
   private Lock bankLock;
   private Condition sufficientFunds;
 
   /**
    * 建设银行。
    * @param n 账号
    * @param initialBalance 每个账户的初始余额
    */
   public Bank(int n, double initialBalance)
   {
      accounts = new double[n];
      Arrays.fill(accounts, initialBalance);
      bankLock = new ReentrantLock();
      sufficientFunds = bankLock.newCondition();//在等待条件前,锁必须由当前线程保持。
   }
 
   /**
    * 把钱从一个账户转到另一个账户。
    * @param 从账户转账
    * @param 转到要转账的账户
    * @param 请允许我向你转达
    */
   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();//解锁。
      }
   }
 
   /**
    * 获取所有帐户余额的总和。
    * @return 总余额
    */
   public double getTotalBalance()
   {
      bankLock.lock();
      try
      {
         double sum = 0;
 
         for (double a : accounts)
            sum += a;
 
         return sum;
      }
      finally
      {
         bankLock.unlock();
      }
   }
 
   /**
    * 获取银行中的帐户数量。
    * @return 账号
    */
   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 = () -> {                //Runnable接口实现创建线程
            try
            {
               while (true)
               {
                  int toAccount = (int) (bank.size() * Math.random());   //随机函数产生
                  double amount = MAX_AMOUNT * Math.random();            //随机函数产生MAX_AMOUNT个随机数
                  bank.transfer(fromAccount, toAccount, amount);         //调用transfer方法在同行之间进行转账
                  Thread.sleep((int) (DELAY * Math.random()));           //随机睡眠时间DELAY
               }
            }
            catch (InterruptedException e)
            {
            }            
         };
         Thread t = new Thread(r);  //创建一个线程
         t.start();                 //该线程开始工作
      }
   }
}

运行结果:

实验1:测试程序2

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)        //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
   {
      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();   //唤醒等待使用该资源的其他线程
   }
 
   /**
    * 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()    //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环境下运行以下程序,结合程序运行结果分析程序存在问题;

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

运行结果:

实验总结:

通过实际操作,进一步体会了线程同步的两种方法,依旧感觉有些吃力.本周主要精力在完成各科目的课程论文,所以在实验上投入时间不足,没有掌握好所学知识。

未来两周会重点查缺补漏JAVA的基础知识,把最基本的技术掌握好。

猜你喜欢

转载自www.cnblogs.com/1377x/p/12085169.html