201871010110- Li Hua "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/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)

I. thread-safe, thread synchronization, thread mutex, thread communication

       Thread-safe: multiple threads of execution means the same code each time single-threaded execution and the results are the same.

       Thread synchronization: Sharing data on critical areas, A thread to manipulate the data, and require another thread B continues operations to complete, this thread is a collaboration between the thread synchronization.

       The thread mutually exclusive: Sharing data on critical areas, two thread has modified the situation, such as if there is no locked or cas operation will cause confusion abnormal data, this is the thread mutually exclusive.

       Thread communication: the expansion can be regarded as a thread synchronization, because wait / notify must acquire the object lock to use, realize by waiting two threads wake wait / notify this way.

II. Thread communication and interprocess communication in several ways

       Thread communication: shared variable, wait / notify, lock / Condition (Condition ReentrantLock by the new condition, which is equivalent to await wait, signal equivalent to notify).

       Interprocess communication: memory mapping, message queues, socket.

7 ways to thread synchronization

synchronized synchronization method. If an ordinary method will lock the object, if it is a static method to lock the whole class.
synchronized synchronized block.
volatile modifying variables.
Reentrant lock ReenreantLock. Lock implements an interface, reentrant, but inefficient.
ThreadLocal thread-level variable share.
Blocking queue LinkedBlockingQueue. Mainly through put synchronized in, take to achieve.
Atomic variables.
Runnable, Thread, Callable, Future, FutureTask, ThreadLocal

       Runnable: is an interface only one run method, when a thread into the running state, it will execute the run method, it can be considered a package to run the task.

       Thread: is a class when the thread enters running state, will execute the run method, if there is no override the default run method calls the Runnable's run method.

       Callable: is an interface, only one method call, and runnable similar, but the difference is there is a return value and can throw an exception.

       Future: an interface. Is runnable, running operating results callable, you can determine whether the operation is completed, whether to cancel the operation and get results, get to run the result of calling the get method, the results obtained in this way are synchronized.

       FutureTask: is an implementation class that implements the Future and Runnable interface. So either as Runnable to start a thread, it can be used as a thread to acquire Future operating results. The main thing is needed, Future is the interface can not directly manipulate operating results, FutureTask can also only Future implementation class.

       ThreadLocal: an internal map, its role is defined as a variable thread-level variables.

Get Thread operating results:

       The use of callable call method can have a return value, generally with ExectorService the submit (callable) method, its return value is the Future, then get the thread running through Future's get method results. Similar Future FutureTask be used instead.

Executor framework:

       Executor framework is a framework for asynchronous execution threads to perform tasks equivalent to the consumer, the thread producers to submit a task equivalent. The main API includes the following:

Executor: actuator interface, only a Execute (Runnable) method, to perform the tasks of a Runnable, but this method does not return a value, less use.
ExecutorService: Executor is sub-interface, is the interface ThreadPoolExecutor parent, the method comprising adding some off, etc., the most important method is to increase the submit (Callable), the return value is Future <T> or FutureTask <T>.
ScheduledExecutorService: ExecutorService is sub-interface, the main method of increasing the number of timed tasks.
ThreadPoolExecutor: JDK thread pool class.
Executors: is a factory class that provides five static methods to create a thread pool.
Race conditions, critical region

       Race condition is the order of the program depends on the results of running thread of execution, a program that is not the result of luck. The most typical race condition is performed after the first inspection, the inspection is in front of an invalid check expired, but the implementation of the code behind.

       The critical area is the access to resources that can have only one thread of execution of code block.

Synchronized、Lock、ReentrantLock、ReadWriteLock 、ReentrantReadWriteLock

       Synchronized JVM is built-in keywords. It can be used in the block process; unfair lock; reentrant lock; unable to respond to the interrupt; performed over the block of code lock or release the lock will automatically interrupt; if holding the lock can not be obtained, a pending thread, etc. information.

       Lock is an interface, the implementation class of ReentrantLock Lock is provided a method of acquiring a lock and unlock method for releasing the lock of the lock, trylock the like; non-default fair lock. It can also be set to lock fair; reentrant lock; responsive to interrupt; need to take the initiative to release the lock, or is likely to occur deadlock; get some information lock.

       ReadWriteLock is another interface, ReentrantReadWriteLock is ReadWriteLock implementation class, the main features are readLock and writeLock kinds of locks also need to take the initiative to release the lock. If a thread lock accounted for reading, it does not affect other threads to acquire a read lock, but if the other thread to obtain a write lock, you need to wait for the completion of read locks; if a thread is accounted for write lock, then other threads acquire the read-write lock needs to wait write lock is released.

Some definitions lock

       Reentrant locks: lock means reentrant succeed immediately when the thread holding the lock again to acquire the lock, the lock count of +1, -1 counts when executing the code block, the lock is released when the count is 0; non-reentrant lock is a situation may lead to a deadlock when the thread holding the lock acquisition again.

       Interruptible lock: Lock is interruptible thread can be interrupted while waiting to acquire the lock, to handle other tasks. Synchronized not interruptible lock, lock that can break a lock.

       (Non) Fair lock: Fair lock means acquire the lock is in order, for example ReentrantLock may be provided by a constructor to fair, while waiting for a long time locks priority access to the lock; unfair lock is acquired regardless of the lock with the sequence selected at random a thread allocation lock, for example, is a typical non-synchronized fair locks, which could lead to unfair lock has been acquired less than a thread lock.

       Exclusive lock \ shared lock (mutex \ read-write lock): exclusive lock means the lock at the same time can only be held by a thread, such as synchronized, ReentrantLock; shared lock is the lock can be held together multiple threads there are, for example ReadWriteLock and its subclasses ReentrantReadWriteLock, which read lock is a shared lock, write lock is an exclusive lock. The mutex lock and read it are the concrete manifestation of the exclusive lock and a shared lock.

       Optimistic lock \ pessimistic locking: optimistic locking is considered little more than read write, so when reading is not locked, it will first execute as usual at the time of writing, when found in the results of this operation will not give up and try again when, for example, CAS algorithm; pessimistic read locks are considered less write more, so every reader will be locked in such an exclusive lock.

       Biased lock, lock lightweight, heavyweight lock: three actually lock the three states and is true synchroinzed terms. Biased locking means is a thread synchronization code has been accessed, then this thread will automatically acquire the lock, the lock is biased locking; lightweight lock is biased locking means that before the corresponding code block is accessed by another thread, then this biased locking will be upgraded to lightweight lock, then thread acquires the lock acquired by way of spin, reducing the consumption of context switches; heavyweight lock means lightweight thread to acquire the lock spin for some time still can not get to when the lock, in order to reduce CPU consumption, will upgrade the lock to lock heavyweight, heavyweight lock when the thread gets into the blocked state.

CAS algorithm

       CAS (Compareand Swap, compare and exchange) is a typical optimistic locking algorithm implementation. Its core is to modify the operation, there will be the old value, the expected value and the new value, old value when to modify memory, and will go to determine whether their expected values ​​are equal, if not equal illustrate modified by another thread directly replaced with the new value; if another thread is not equal described modified, to discard this operation. In this way the lock case can be optimized to improve efficiency, but may also occur ABA (A B value is changed, there is changed to A, CAS can not be found) the.

6 Ways lock optimization

(Reduce lock holding time) refined lock. Reducing the locked block of code, as part of the code locking The longer the operating time, the longer the waiting time another thread.
(Reducing lock granularity) lock segment. ConcurrentHashMap example, to achieve a plurality of inner segment (reentrantLock subclass), by the segment table to improve performance.
Coarsening lock. Heavyweight locks wait for a thread to enter the blocked state, the thread context switching overhead increases, so frequent use of the lock as a lock is not coarser particle size, although a single lock long running time, but reducing the CPU overhead.
Spin lock. Wait for a short time lock.
Lock separation. For example, read-write lock ReadWriteLock, end to end, or two LinkedBlockingQueue maintain lock.
Lock eliminated. JIT will not be shared object to eliminate the lock at compile time.

synchronized keyword

the role of the synchronized keyword:

After a certain class synchronized modifying method, this method is called a 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 from the preamble method returns wake blocked threads, other threads parties may enter synchronization method.

 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.

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.

 

Test Procedure 1:

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

code show as below:

Synch Package Penalty for; 

/ ** 
 * This program demonstrates how to secure access to multi-threaded data structures. 
 2015-06-21 @version 1.31 * 
 * @author Cay Horstmann 
 * / 
public class SynchBankTest 
{ 
   public static int NACCOUNTS Final = 100; 
   public static Double Final INITIAL_BALANCE = 1000; 
   public static Double Final MAX_AMOUNT = 1000; 
   public static int the DELAY = Final 10; 
   
   public static void main (String [] args) 
   { 
      Bank Bank = new new Bank (NACCOUNTS, INITIAL_BALANCE); 
      for (int I = 0; I <NACCOUNTS; I ++) 
      { 
         int fromAccount = I; 
         // can capture the abnormal InterruptedException 
         R & lt = the Runnable () -> {  
            the try
            {
               the while (to true) 
               { 
                  int toAccount = (int) (bank.size () * Math.random ()); 
                  Double MAX_AMOUNT AMOUNT * = Math.random (); 
                  bank.transfer (fromAccount, toAccount, AMOUNT); 
                  the Thread.sleep ((int) (Math.random the DELAY * ())); 
               } 
            } 
            the catch (InterruptedException E) 
            { 
            }             
         }; 
         // RUN method runnable class continuously removed money from a bank account fixed 
         // every time iteration, randomly select a RUN and a random account destination account, and the bank object call transfer method, and then sleep 
         the Thread the Thread new new T = (R & lt); 
         t.start ();  
      }
   } 
}

 

  

Synch Package Penalty for; 

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

/ ** 
 * bank has multiple bank accounts using locks to serialize access. 
 2004-08-01 @version 1.30 * 
 * @author Cay Horstmann 
 * / 
public class // Bank with a lock to protect the transfer method Bank class; 
{ 
   Private Final Double [] Accounts; 
   Private Lock bankLock; 
   Private for condition Condition sufficientFunds; 

   / * * 
    * Constructs the Bank. 
    * @ param n-number of the account 
    opening balance * @param initial account balance of each 
    * / 
   public Bank (n-int, Double initialBalance) 
   { 
      accounts new new Double = [n-]; 
      Arrays.fill (accounts, initialBalance );
      bankLock = new ReentrantLock (); // ReentrantLock constructed with a lock fairness policy 
      sufficientFunds = bankLock.newCondition (); // a method of obtaining one condition newCondition objects 
   } 

   / ** 
    * transferring funds from one account to another account. 
    * To transfer the account parameters @ 
    * @ to be transferred to the account parameters 
    * @ param amount of money to be transferred 
    * / 
   public void Transfer (int from, int to, Double AMOUNT) throws InterruptedException 
   { 
	   // check by using locks of love and protection transfer action to do this 
      bankLock.lock (); 
      the try 
      { 
         the while (Accounts [from] <AMOUNT) 
            sufficientFunds.await (); // lack of balance, call sufficientFunds.await () so that the current thread blocked 
         System.out.print (Thread.currentThread ()); 
         Accounts [from] - = AMOUNT;
         System.out.printf ( "% 10.2f% from D to D%", AMOUNT, from, to); 
         Accounts [to] + = AMOUNT; // two threads execute instructions simultaneously 
         System.out.printf ( "Total Balance :% n-% 10.2f ", getTotalBalance ()); 
         sufficientFunds.signalAll (); 
      } 
      the finally 
      { 
         ; bankLock.unlock () 
      } 
   } 

   / ** 
       Total * Get all account balance. 
    Returns the total balance * @ 
    * / 
   public Double getTotalBalance () 
   { 
      bankLock.lock (); // with the basic structure of the protective ReentrantLock code block 
      the try 
      { 
         Double SUM = 0; 

         for (Double A: Accounts) 
            SUM = A +;

         SUM return; 
      } 
      the finally 
      { 
         bankLock.unlock (); 
         // The Sure Lock the make the even IF Unlocked IS IS AN thrown Exception 
      } 
   } 

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

 

operation result:

Lock objects :

    If two threads try to put a Bank asked the same objects (each Bank has a lock), then the lock will be served in a serial manner; however, if two threads access different Bank objects, each thread will get a different the objects, the two threads are not clogged.

Locks are reentrant, because the threads can be repeated to obtain the lock was already held. Holding a lock to hold the count of the track lock nested methods. Each thread calls the lock method will increase the count, the count each call Unlock will decrease due to this feature, protected by a lock code can call another method using the same lock.

For example, in our final code, Transfer method calls getTotalBalance method, which also blocked bankLock objects, objects held by the lock case bankLock count of 2. When getTotalBalance method exits, holding the count back to 1. When the transfer method exits, hold count becomes zero, the thread releases the lock.

Criteria object
   of the program was locked, thus avoiding some of the circumstances that make us sad, but in fact, what we want is often more complex than than we now imagine: a thread banks entered the critical zone, he wanted to be withdraw money to operate, but found there is not enough money can be removed (possibly wages have not hit on the user's account), only enough money to pay to go, but he is now on the Bank of the object itself was locked, so other threads have no right to object to the operation of the Bank, then, you need to use the condition objects.

Test Procedure 2:

Debugging 655 teaching program 14-8 in Elipse environment, combined result of the program understand the program;

code show as below:

synch2 Package Penalty for; 

Import synch.Bank; 

/ ** 
 * This program demonstrates how to secure access to multi-threaded data structures. 
 2015-06-21 @version 1.31 * 
 * @author Cay Horstmann 
 * / 
public class SynchBankTest2 
{ 
   public static int NACCOUNTS Final = 100; 
   public static Double Final INITIAL_BALANCE = 1000; 
   public static Double Final MAX_AMOUNT = 1000; 
   public static int the DELAY = Final 10; 
   
   public static void main (String [] args) 
   { 
      Bank Bank = new new Bank (NACCOUNTS, INITIAL_BALANCE); 
      for (int I = 0; I <NACCOUNTS; I ++) 
      { 
         int fromAccount = I; 
         // can capture the abnormal InterruptedException
         R & lt = the Runnable () -> { 
            the try 
            { 
               the while (to true) 
               { 
                  int toAccount = (int) (bank.size () * Math.random ()); 
                  Double MAX_AMOUNT AMOUNT * = Math.random (); 
                  bank.transfer ( fromAccount, toAccount, AMOUNT); 
                  the Thread.sleep ((int) (Math.random the DELAY * ())); 
               } 
            } 
            the catch (InterruptedException E) 
            { 
            }             
         }; 
         // RUN runnable class method, continuously from a fixed money out of bank accounts 
         // at each iteration, run randomly select a target account and a random account, call the bank and transfer the object method, then sleep
         Thread t = new Thread(r);
         t.start();
      }
   }
}

  

synch2 Package; 

Import Classes in java.util *;. 

/ ** 
 * bank having a plurality of synchronization primitives using bank account 
 * @version 1.30 2004-08-01 
 * @author Cay Horstmann 
 * / 
public class Bank 
{ 
   Private Double Final [ ] accounts; 

   / ** 
    . * Constructs the Bank 
    * @param n-Number of accounts the 
    initial balance * @param initial parameters for each account balance 
    * / 
   public Bank (n-int, Double initialBalance) 
   { 
      accounts new new Double = [n-] ; 
      Arrays.fill (accounts, initialBalance); 
   } 

   / ** 
       * transferring funds from one account to another. 
    * To transfer the account parameters @ 
    * @ to be transferred to the account parameters 
    * @ param amount of money to be transferred 
    * /
   Transfer synchronized void public (int from, int to, Double AMOUNT) throws InterruptedException 
   { 
	   // Each object has an internal lock, and the lock has an internal condition 
	   // managed by the lock mentoring those threads into the synchronized method, the condition management of those threads wait to call 
      the while (Accounts [from] <AMOUNT) 
         wait (); 
      of System.out.print (Thread.currentThread ()); 
      Accounts [from] - = AMOUNT; 
      System.out.printf ( "% % 10.2f% to D from D ", AMOUNT, from, to); 
      Accounts [to] + = AMOUNT; 
      System.out.printf (" the Total Balance:% n-% 10.2f ", getTotalBalance ()); 
      notifyAll () ; 
   } 

   / ** 
       * Get the sum of all of the account balance. 
    @Return at The Total Balance * 
    * /
   Double getTotalBalance the synchronized public () 
   { 
      Double SUM = 0; 

      for (Double A: Accounts) 
         SUM = A +; // Get the total 

      return SUM; 
   } 

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

  

Run shot:

 

Synchronized
       just from a linguistic point of view, to synchronize threads, or solve a shared resource competition is simply that in case of conflict, when resources are using a task (Thread), on which you can add lock . The lock has a JVM is complete, we do not need to care, using Synchronized said to add to this resource lock. On actual development, this "resource" is the code together in our approach or method.

       Synchronized use of resources to achieve the mutex locking mechanism, the sequence of essentially all of the thread concurrency model in solving conflict, and are based on the shared resources program. This means that only one task at a time to allow access to shared resources. This is often before the code with a lock statement to achieve, which makes only one task can run this code at a time.

       Or from another angle, from an OS perspective, our competition is to thread the same piece and the memory read and write operations, which is the memory resources. And this child memory resources are represented in Java as a variable, an object. Of course, a shared resource can be a file, I / O, printer and so on. All methods to control the sharing of resources, it had to first be packaged into an object, then all you want to access this resource labeled Synchronized. And this object will be automatically given a JVM lock, which is the object lock.

Test Procedure 3:

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

code show as below:

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;          //用InterruptedException捕获异常
    	      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
{
 static void main public (String args []) 
  { 
   the Customer = new new Customer1 the Customer (); 
   the Customer = new new Customer2 the Customer (); 
   customer1.start (); 
   customer2.start (); // call the Start method of the Thread class open thread 
  } 
}

  

Run shot:

 After solving the code:

package Test;

class Cbank
{
     private static int s=2000;
     public  synchronized static void sub(int m)//用synchronized来解决冲突问题
     {
           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();
  }
}

  

运行截图:

程序在运行时有冲突发生,所以利用synchronized

     使得只要某个线程正在访问同步方法,其他线程欲要访问同步方法就被阻塞,直至线程从同步方法返回前唤醒被阻塞线程,其他线程方可能进入同步方法。

实验2 编程练习

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

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

1)   程序设计思路简述;

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

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

package Test;
public class Ticket {
    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分)

 本周学习了有关线程的剩余的知识点,通过老师上课的讲解以及对课本示例代码的编辑和运行,掌握了线程同步的概念及实现技术,面对多线程并发运行不确定性问题解决方案:需要引入线 程同步机制,使得另一线程要使用该方法,就只 能等待。线程同步主要是解决多线程并发运行不确定性问题。还在示例代码中学习了ReentrantLock类,在共享内存的类方法前加synchronized修饰符的方法,对synchronized有了一定的了解,通过最后的Java线程综合编程练习对这些知识点有了更清晰的认识,所以在之后还得在课后多加练习和复习,才能有一定的记忆基础。

Guess you like

Origin www.cnblogs.com/LH-18110/p/12072996.html