201871010116- Qi British Red "object-oriented programming (java)" Week 17 learning summary

Bowen beginning of the text format: (2 points)

project

content

"Object-oriented programming (java)"

https://home.cnblogs.com/u/nwnu-daizh/

Where this requirement in the job

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

Essay Bowen body content include:

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

Thread Synchronization

Multi-threaded run concurrently uncertainties solution: the introduction of thread synchronization mechanism, so that another thread To use this method, you can only wait.

 The solution multi-thread synchronization in Java, there are two:

1.- Java SE 5.0 ReentrantLock introduced class.

2.- synchronized modifier was added before the shared memory-based method.

……

public synchronized static void sub(int m)

……

Solution one: lock object and condition object

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

myLock.lock();

try {

   critical section

} finally{

myLock.unlock(); }

The key points about the lock object and condition object:

1, to protect the lock code segments, to ensure that any time only one thread is executing code in protected.

2, the lock manager thread is trying to enter the protection code segment.

3, the lock may have one or more conditions related objects.

4, each condition object management thread that has entered the protected code segment but can not run.

Solution two: synchronized keyword

the role of the synchronized keyword:

1, after a certain class synchronized modification method, which is called a synchronization method;

2, 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 parties may enter synchronization method.

3, when a thread synchronization method used, it may be necessary problem, you must use the wait () method to make this thread to wait temporarily give up the right to use the CPU, and allow other threads to use this synchronization method.

4. If you run out of thread synchronization method should be executed notifyAll () method notifies all synchronization due to the use of this method in the waiting thread waiting for the end.

Object lock

(1) synchronized process (lock current object)

(2) synchronized block of code (for a lock of an object)

If the synchronization code block must be used to set the object to be locked, it is generally possible to lock the current object: this.

(3) synchronized multi-object lock

When a plurality of objects can not be synchronized synchronization lock operation, the lock can be obtained thereby are synchronized acquired the object lock key, rather than a piece of code or a method (function) as a lock.

Global Lock

There are two ways to achieve global lock:

(1) The keywords used in the synchronized static method

Synchronized static methods applied to the static type Class is locked, synchronized and non-static approach is applied to the object lock. Class lock may for instance function for all object classes.

(2) to lock the object synchronized with the class of Class

Acting synchronized (class) of the code block with the same effect synchronized static method.

Multithreaded access synchronized eight methods:

A: two threads simultaneously access an object's synchronized method, synchronous execution;

II: two threads access the synchronized method two objects, in parallel;

Three: two threads simultaneously access a synchronized static method, synchronous execution;

Four: two threads simultaneously access the synchronized and non-synchronized method method, concurrent execution;

Five: synchronized method two different threads access the same object, synchronous execution;

Six: two threads access static synchronized methods and non-static synchronized method, parallel execution;

Seven: Methods throw exceptions, it will release the lock;

Eight: call synchronized methods in a general way, not thread-safe, synchronized range only role in "{}" inside;

Part II: Experimental part

Experiment 1: Test Procedure 1 (5 min)

package synch;

import java.util. *;
import java.util.concurrent.locks.*;

/**
Many banks have a bank account, using a lock to serialize access * @version 1.30 2004-08-01
 * @author Cay Horstmann
 */
public class Bank
{
   private final double[] accounts;
   private Lock bank lock;
   private Condition sufficientFunds;

   /**
    * Construction Bank.
    * @Param n account
    * @Param initialBalance initial balance of each account
    */
   public Bank(int n, double initialBalance)
   {
      accounts = new double[n];
      Arrays.fill(accounts, initialBalance);
      bank lock = new ReentrantLock ();
      sufficientFunds = bankLock.newCondition (); // wait condition before, the lock must be held by the current thread.
   }

   /**
    * The money from one account to another.
    * @Param from the account transfers
    * @Param to be transferred to the account
    * @Param Allow me to convey to you
    */
   public void transfer(int from, int to, double amount) throws InterruptedException
   {
      bankLock.lock (); // lock
      try
      {// Lock the object object reference conditions
         while (accounts[from] < amount)
            sufficientFunds.await (); // result has been in a waiting state until the current thread is signaled or interrupted.
         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 (); // if all threads are waiting on this condition, then wake up all threads
      }
      finally
      {
         bankLock.unlock (); // unlock.
      }
   }

   /**
    * Get the sum of all account balances.
    * @Return total balance
    */
   public double getTotalBalance()
   {
      bankLock.lock ();
      try
      {
         double sum = 0;

         for (double a : accounts)
            sum += a;

         return sum;
      }
      finally
      {
         bankLock.unlock ();
      }
   }

   /**
    * Get the number of accounts in the bank.
    * @Return account
    */
   public int size()
   {
      return accounts.length;
   }
}

  

package synch;

/**
 * This program shows how to safely multiple threads access the 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 ())); // currently executing thread to sleep in a specified number of milliseconds
               }
            }
            catch (InterruptedException e)
            {
            }            
         };
         Thread t = new Thread(r);
         t.start (); // start the thread execution
      }
   }
}

  Results are as follows:

The key points about the lock object and condition object:

1, to protect the lock code segments, to ensure that any time only one thread is executing code in protected.

2, the lock manager thread is trying to enter the protection code segment.

3, the lock may have one or more conditions related objects.

4, each condition object management thread that has entered the protected code segment but can not run.

Experiment 1: Test Procedure 2 (5 minutes)

package synch2;

import java.util. *;

/**
 * The use of synchronization primitives have multiple bank accounts of the bank.
 * @version 1.30 2004-08-01
 * @author Cay Horstmann
 */
public class Bank
{
   private final double[] accounts;

   /**
    * Construction Bank.
    * @Param n account
    * @Param initialBalance initial balance of each account
    */
   public Bank(int n, double initialBalance)
   {
      accounts = new double[n];
      Arrays.fill(accounts, initialBalance);
   }

   /**
    * The money from one account to another.
    * @Param from the account transfers
    * @Param to be transferred to the account
    * @Param Allow me to convey to you
    */
   public synchronized void transfer(int from, int to, double amount) throws InterruptedException
   {
      while (accounts[from] < amount)
         wait (); // add a thread to wait for a centralized
      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 (); // unblock the current thread
   }

   /**
    * Get the sum of all account balances.
    * @Return total balance
    */
   public synchronized double getTotalBalance()
   {
      double sum = 0;

      for (double a : accounts)
         sum += a;

      return sum;
   }

   /**
    * Get the number of accounts in the bank.
    * @return 
    */
   public int size()
   {
      return accounts.length;
   }
}

  

package synch2;

/**
 * 
 * This program demonstrates how to use multiple threads synchronization method for secure access to the data structure.
 * @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; // inner class using
         Runnable r = () -> {
            try
            {
            	while (true)
                {
                   int toAccount = (int) (bank.size () * Math.random ()); // out a random account
                   double amount = MAX_AMOUNT * Math.random (); // set a random sum of money
                   bank.transfer (fromAccount, toAccount, amount); // transfer operation
                   Thread.sleep ((int) (DELAY * Math.random ())); // random sleeping time
                }
            }
            catch (InterruptedException e) // throw an exception
            {
            }
         };
         Thread t = new Thread(r);
         t.start();
      }
   }
}

  Results are as follows:

Multithreaded access synchronized eight methods:

A: two threads simultaneously access an object's synchronized method, synchronous execution;

II: two threads access the synchronized method two objects, in parallel;

Three: two threads simultaneously access a synchronized static method, synchronous execution;

Four: two threads simultaneously access the synchronized and non-synchronized method method, concurrent execution;

Five: synchronized method two different threads access the same object, synchronous execution;

Six: two threads access static synchronized methods and non-static synchronized method, parallel execution;

Seven: Methods throw exceptions, it will release the lock;

Eight: call synchronized methods in a general way, not thread-safe, synchronized range only role in "{}" inside;

Experiment 1: Test Procedure 3 (5 minutes)

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

Results are as follows:

The improved code is as follows:

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

  Results are as follows:

实验2:结对编程练习包含以下4部分(10分)

结对伙伴:李华

1)   程序设计思路简述;

    程序的主要设计思路没有太繁琐,只是新建三个售票口,在thread类中创建线程并开启线程,然后在run方法中定义线程任务,进行异常处理后设计在10张票数内时将售票情况进行打印,票数超过10张时程序结束;

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

package math;

public class Demo {
    public static void main(String[] args) {
        Mythread mythread = new Mythread();
        Thread ticket1 = new Thread(mythread);
        Thread ticket2 = new Thread(mythread);
        Thread ticket3 = new Thread(mythread);//新建三个Thread类对象
        ticket1.start();
        ticket2.start();
        ticket3.start();//调用thread类的start方法来开启线程
    }
}

class Mythread implements Runnable {//实现runnable接口进行线程的创建
    int ticket = 1;
    boolean flag = true;

    @Override
    public void run() {//将线程任务代码定义到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++;//票数在10张之内时,进行打印直到售出10张票时停止
                }
                if (ticket > 10) {
                    flag = false;
                }
            }
        }
    }

}

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

 

实验总结:(5分)

在本周的学习中,我学习了线程同步这一知识点,我了解到这一知识点是用来解决多线程并发运行不确定性问题。学习了解决多线程同步问题的两种方案,分别是锁对象与条件对象引用和 synchronized关键字。在实验课上收获了当注释调代码sufficientFunds.await();会出现死锁状态等知识,感受颇多。注意点有:线程如果用完同步方法,应当执行notifyAll()方 法通知所有由于使用这个同步方法而处于等待的 线程结束等待。线程如果用完同步方法,应当执行notifyAll()方 法通知所有由于使用这个同步方法而处于等待的 线程结束等待。以后会坚持学习Java。

Guess you like

Origin www.cnblogs.com/qyhq/p/12078285.html