201871010113- Liuxing Rui "object-oriented programming (java)" Week 17 learning summary

 

 

project

content

This work belongs courses

<Classroom teachers blog Home Links> https://www.cnblogs.com/nwnu-daizh/

Where this requirement in the job

<Job link address> https://www.cnblogs.com/nwnu-daizh/p/12073034.html

Job learning objectives

(1) understand and master the property and priority scheduling method thread;

(2) to grasp the concept and implementation of thread synchronization technology;

(3) Java threads comprehensive programming exercises

 

Part I: summary of thread synchronization technology

 

1.Java run concurrently by multiple threads to improve utilization of system resources, improve system performance.

2. Assuming there are two or more threads share an object, each thread calls a method to change the state of the object class, it will cause uncertainty.

3. Multi-threaded implementation issues

◆ relative order of execution of multiple threads is uncertain.

◆ thread execution order uncertainty create uncertainty in the results.

◆ often generate this uncertainty in a multi-threaded operations on shared data.

4. Multi-threaded run concurrently uncertainties solution: the introduction of thread synchronization mechanism.

5. (1) and a condition object lock object

           The basic structure of the protective ReentrantLock code block with the following:

           myLock.lock();

           try { critical section }

           finally{

           myLock.unlock();

   }

   (2) synchronized keyword

          the role of the synchronized keyword:

         ➢ a class after the synchronized method modified method is referred to as the synchronization method;

         ➢ As long as a thread is accessing the synchronization method, other threads want to access the synchronization method will be blocked until the thread wakes up the blocked thread synchronization method returns from the front, the other party may enter the thread synchronization method.

Part II: Experimental part

1 , experimental purposes and requirements

(1) Grasp the concept and implementation of thread synchronization technology;

(2) comprehensive programming practice thread

2 , experimental and step

Experiment 1: Test procedures and code comments.

Test Procedure 1:

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

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

Note experiment code as follows:

Bank.java:

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 of ReentrantLock new new = (); 
      sufficientFunds bankLock.newCondition = (); // wait condition before, the lock must be held by the current thread. 
   } 

   / ** 
    * Transfers Money to Account from One Another. 
    * @Param from The Account Transfer to from 
    * @param to The Account Transfer to to 
    * @param to AMOUNT AMOUNT The Transfer 
    * / 
   public void Transfer (int from, int to , Double AMOUNT) throws InterruptedException 
   { 
      bankLock.lock (); // get lock 
      the try 
      { 
         the while (Accounts [from] <AMOUNT) 
            sufficientFunds.await (); // causes the current thread has been in a prior interrupt is signaled or wait status.
         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 (); // if all of the threads waiting on the condition, the wake up all threads 
      } 
      the finally 
      { 
         bankLock.unlock (); // release the lock. 
      } 
   } 

   / ** 
    * Gets, Account Balances The SUM of All. 
    * @Return The Total Balance 
    * / 
   public Double getTotalBalance () 
   { 
      bankLock.lock (); 
      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;
   }
}

  SynchBankTest.java:

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

Results are as follows:

Test Procedure 2:

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

grasp synchronized application of multi-thread synchronization.

Note experiment code as follows:

Bank.java:

 

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.
    The Account to @param from * Transfer from 
    * @param to The Account Transfer to to 
    * @param to AMOUNT AMOUNT The Transfer 
    * / 
   public void the synchronized Transfer (int from, int to, Double AMOUNT) throws InterruptedException 
   { 
      the while (Accounts [from ] <AMOUNT) 
         the wait (); // call this object before in other threads notify () method or the notifyAll () method causes the current thread to 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 ( "the Total Balance:% 10.2f% n-", getTotalBalance ()); 
      notifyAll (); // wake up all threads waiting on this object monitor 
   } 

   / **
    * 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;
   }
}

 

SynchBankTest2.java:

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

Code results are as follows:

 

Test Procedure 3:

l Elipse run the following program in the environment, in conjunction with the results of analysis program running problems;

l try to resolve program problems.

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

  }

}

代码运行结果如图:

运行结果显示两个线程各自运行各自的:并没有实现需要的两个线程一起每次减一百,减八次。

修改代码如下:

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分)

1)   程序设计思路简述;

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

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

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

 代码如下:

import javax.swing.plaf.SliderUI;

public class shou {
public static void main(String[] args) {
 Mythread mythread=new Mythread();
 Thread t1=new Thread(mythread);
 Thread t2=new Thread(mythread);
 Thread t3=new Thread(mythread);
 t1.start();
 t2.start();
 t3.start();
}
}
 /*
    new Thread() {
        @Override
        public void run() {
            System.out.println();
    };
}.start();
}
}*/

class Mythread implements Runnable{
int t=1;
boolean flag=true;
    @Override
    public void run() {
        while(flag) {
            try {
        
            Thread.sleep(500);
            }
            catch (InterruptedException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            synchronized (this) {
            if(t<=10) {
                System.out.println(Thread.currentThread().getName()+"窗口售:第"+t+"张票");
                t++;
            }
            if(t<0) {
                flag=false;
            }
        }
    }
    }
}

    

运行结果如图:

实验总结;通过本次实验,我学习到了线程同步的概念,以及如何处理。通过本学期的学习,由刚开始的新手小白,对Java一无所知,到通过大量的练习慢慢对Java编程有所熟悉,虽然现在还不是很熟练,但在课程结束后仍需继续关注学习Java的知识及编程。

Guess you like

Origin www.cnblogs.com/lxr0/p/12074639.html