201871010119- posts Jiaojiao "object-oriented programming (java)" Week 17 learning summary

Bowen beginning of the text format: (2 points)

project

content

This work belongs courses

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

Where this requirement in the job

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

Job learning objectives

(1) and common control menu component uses the API;

(2) Common control box assembly and use the API;

(3) learn to design simple application GUI.

Essay Bowen body content include:

First part: summary of thread synchronization techniques (10 minutes)

19, thread synchronization:

  Multi-threaded run concurrently uncertainties solution:

  The introduction of thread synchronization mechanism;

There are two in Java thread synchronization methods:

(1) JavaSE5.0 introducing ReentrantLock class;

20, lock objects and conditions relating to the object of the key points:

  Lock for protection code fragment, to ensure that at any time only one thread protection code is executed;

  Lock Manager thread attempting to enter the protected code segment;

  Lock condition can have one or more associated objects;

  Each condition object management thread that has entered a code segment but can not run to get protected;

21, the conditions of use of the object in the critical area await (), signal (), signalAll () method to achieve interaction between threads:

  A thread in the critical zone, may on an issue, you must use the lock object await () method to make this thread to wait temporarily give up the right to use the CPU, and allow other threads to use the synchronization method;

  If the thread exits the critical section, the application of signal () method of randomly selecting a thread unblock;

  If the thread exits the critical region, execution notifyAll () method notifies all waiting for this critical area due to the end of the thread waits.

(2) was added before the synchronized modifier shared memory class methods;

  the role of the synchronized keyword:

  After a certain class synchronized modifier method, the method is referred to synchronize threads;

  As long as a thread is accessing the synchronization method, other threads want to access the synchronization method will be blocked until the thread from the preamble method returns wake blocked threads, other threads may enter synchronization method method;

Part II: Experimental part

Experiment 1: Test Procedure 1 (5 min)

l 651 program debugging textbooks 14-7 in Elipse environment, combined result of the program understand the program;

l mastered the use of multithreading synchronization lock objects and conditions for realization of the object.

Experiment code is as follows:

Synch Package; 

Import Classes in java.util *;. 
Import in java.util.concurrent.locks *;. 

/ ** 
 . * A A Number of Bank with Bank Accounts that uses Locks for serializing Access 
 * @version 1.30 2004-08-01 
 * Cay Horstmann @author 
 * / 
public class Bank 
{ 
   Private Final Double [] accounts; // array of storage account 
   private Lock bankLock; // attribute of the object, and two classes standard synchronous control 
   private condition sufficientFunds; // condition object 
// 
   / ** 
    * Constructs The Bank. 
    * @param The n-Number of Accounts 
    * @param initialBalance The Initial for each Account Balance 
    * / 
   public Bank (n-int, Double initialBalance) // constructor Bank, two inlet parameters 
   { 
      Accounts new new Double = [n-];
      Arrays.fill (Accounts, initialBalance); 
      bankLock of ReentrantLock new new = (); // construct can be used to protect a critical section of the reentrant lock. 
      sufficientFunds = bankLock.newCondition (); // Returns an object related to the condition of lock 
   } 

   / ** 
    . * Transfers Money to Account from One Another 
    * @param from The Account Transfer to from 
    * @param to The Account Transfer to to 
    the AMOUNT AMOUNT to @param * Transfer 
    * / 
   public void Transfer (int from, int to, Double AMOUNT) transfer operation between peer throws InterruptedException // 
   { 
      bankLock.lock (); // locking operation 
      the try 
      { 
         the while (Accounts [from] <amount) // when the account balance is insufficient
            sufficientFunds.await (); // this thread wait set on condition, the current thread is blocked, and discards lock 
   public Double getTotalBalance () // use of public resources
         Of 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 ( "the Total Balance:% n-% 10.2f", getTotalBalance ()); 
         sufficientFunds.signalAll (); // release all the blocked thread 
      } 
      the finally 
      { 
         bankLock.unlock (); / / release the lock 
      } 
   } 

   / ** 
    * Gets, Account Balances the SUM of All. 
    * @return the Total Balance 
    * / 
   { 
      bankLock.lock (); // locking operation 
      the 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;
   }
}

  

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 interface to create a thread 
         the thread the thread new new T = (R & lt); // Create a thread
            try
            { 
               The while (to true) 
               { 
                  int toAccount = (int) (bank.size () * Math.random ()); // random function generating 
                  double amount = MAX_AMOUNT * Math.random () ; // generates a random function random MAX_AMOUNT number 
                  bank.transfer (fromAccount, toAccount, amount) ; // call transfer method transfers between peer 
                  Thread.sleep ((int) (DELAY * Math.random ())); // random sleep time the DELAY 
               } 
            } 
            the catch (InterruptedException E) 
            { 
            }             
         };
         t.start (); // this thread to begin work 
      } 
   } 
}

  Results are as follows:

Experiment 1: Test Procedure 2 (5 minutes)

l 655 program debugging textbooks 14-8 in Elipse environment, combined result of the program understand the program;

Application synchronized in a multithreaded synchronization of l grasp.

Experiment code is as follows:

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

  运行结果如下:

实验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)   程序设计思路简述;

在主函数当中创建三个线程,写一个线程类,是实现Runnable接口的类,调用synchronized关键字实现线程的同步。

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

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

 实验代码如下:

class thread 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;
                }
            }
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        thread mythread = new thread();
        Thread ticket1 = new Thread(mythread);
        Thread ticket2 = new Thread(mythread);
        Thread ticket3 = new Thread(mythread);
        ticket1.start();
        ticket2.start();
        ticket3.start();
    }
}

  运行结果如下:

实验总结:(5分)

  本周学习了线程的知识,这次作业主要是关于同步线程的知识。上课通过老师的讲解代码以及运行结果的分析,对同步线程又了一定的理解,掌握了线程同步的两种方法。(1)引入ReentrantLock类;(2)在共享内存中的类方法前加synchronized修饰符;

  synchronized关键字作用: 某个类内方法用synchronized修饰符后,该方法被称为同步线程; 只要某个线程正在访问同步方法,其他线程欲要访问同步方法就会被阻塞,直至线程从同步方法返回前唤醒被阻塞线程,其他线程方法可能进入同步方法.编程练习是对同步线程的应用。

 

Guess you like

Origin www.cnblogs.com/-8tjj/p/12072156.html