201871010102- often cloudy "object-oriented programming (java)" Week 17 learning summary

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.

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

       1. The program is a piece of static code, which is modeled on the execution of the application. It is a dynamic process of implementation of the program, which corresponds to the load from the code, to perform a complete process is finished. The operating system allocates space for a separate memory and system resources for each process, including: stack code data and other resources. Internal data and the status of each process is completely independent. Multi-tasking operating system, the process of switching to a larger CPU resource consumption.

  2. Multithreading is a number of clues to the implementation of a process's execution generated. A thread is executed smaller units than the process. Thread can not exist independently, they must exist in the process, among threads of the same process of data sharing process space. Each thread has its own production, existence and demise of the process, is a dynamic concept. Multi-line statement means that a multithreaded program can run simultaneously looked almost at the same time. Thread creation, destruction and load switching is much smaller than the process, also known as lightweight processes.

  3. Java multi-threaded in two ways: create a subclass of the Thread class; defined class that implements the Runnable interface in the program.

     4. Create a thread Thread subclasses: first need a class derived from Thread subclass, override run () method in this subclass. Then create objects of this subclass Lefthand left = new Lefthand (); Righthand right = new Righthand (); and finally () method starts with left.start thread start (); right.start ();

  5. Create a subclass Thread multithreading critical operations: Thread defined subclasses and implement user-threaded operation, i.e., run () method is implemented. Start the thread at the appropriate time. Because Java only supports single inheritance, class defined in this way can no longer inherit other parent.

     6. () interface thread with a Runnable: First, design a class that implements the interface Runnable; then in the class needed to rewrite the run method; then create a class object, the object in order to establish the object of the Thread class as a parameter; call the Thread class start the thread start method of the object, it will be forwarded to the CPU executes the right to run method.

     7.Thread (Runnable r): create a new thread, it calls the run r (), r is an instance of a class implements Runnable interface.

     8. The method compares two ways to create threads: realize the benefits of the Runnable interface: in line with OO design ideas; easy to inherit other classes use extends. The advantage of using the method of the Thread class inheritance: simple code.

     9. termination of the thread: After performing the method when the body of the run method of the thread in the last statement, or there has been an exception in the run method does not capture the thread will terminate, so that the CPU usage rights. Call interrupt () method can terminate the thread. void interrupt (): sends an interrupt request to a thread, and this thread is "interrupted" status is set to true. If the thread is blocked state, it will throw InterruptedException.

  10. A method of testing whether or not the interrupted threads: static boolean interrupted (): detecting whether the current thread has been interrupted, and reset the state "interrupted" is false. boolean isInterrupted (): detect whether the current thread has been interrupted, without changing the state of "interrupted" by using the value of a state transition of each thread, each thread can be controlled using the CPU in turn, reflect the characteristics of multi-threaded parallelism.

       11. The thread has the following seven states: New (New); the Runnable (run); Running (running); Blocked (blocked); Waiting (waiting); Timed waiting (wait timer); Terminated (terminated).

 

new (New): thread object just created, has not started, then the thread is still in the non-operational state. For example: Thread thread = new Thread (r); in this case a new thread the thread state, with the corresponding memory space and other resources.

runnable (run state): At this point the thread has been started, in a run in the thread method () . At this time, the thread may run or may not run as long as a CPU is idle, it will soon run. The calling thread's start () method allows the thread is "runnable" state. For example: thread.start ();

       12. blocked (blocked): an executing thread due to special reasons, be suspended into the blocked state. When the thread can not enter a blocking queue, it must wait until the elimination of the cause of obstruction before they can re-enter the queue line. Causes of obstruction are many different reasons to use different methods to lift. sleep (), wait () method are two common causes threads blocked.

       13. The thread blocked three conditions: Wait blocking: () method wait by the calling thread, so thread waits for completion of a job. Synchronous blocking: get synchronized thread synchronization lock failure (because the lock was occupied by another thread), it will enter synchronous blocking state. Other blocking: The sleep () or join the calling thread () or issued I / O request, the thread into the blocked state. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O processing is completed, the thread into the ready state again.

    14. Terminated (terminated): There are two reasons thread has been terminated: First run () method in the last statement is finished and died of natural causes. Second, because without capture of aborted the run method and accidental death. The calling thread can stop way to kill a thread (thread.stop ();), however, stop method is obsolete and do not call it in your own code.

       15. Java thread scheduling uses priority policies: first implementation of high priority, low priority after execution; multithreaded system will automatically assign a priority, and default for each thread, succeeded his father priority class ; mission-critical threads, the higher the priority; the same priority thread queue according to the principle "first in first out" of.

       16.Thread Thread class has three static amount related to the priority: MAX_PRIORITY: the highest priority, is 10; MIN_PRIORITY: minimum priority value of 1; NORM _PRIORITY: default priority value is 5.

Call setPriority (int a) reset the priority of the current thread, a value can be static three aforementioned amount. Call getPriority () to get the current thread priority.

  17. Under the following situations, the currently running thread will relinquish CPU: thread calls yield () or sleep () method; under preemptive system, high-priority thread scheduling participate; because of the current thread I / O access, external memory read and write, waiting for user input and other operations leads to blocking thread; or is waiting for a condition variable, and the thread calls wait () method.

  18. Use only daemon threads is to provide services to other threads. For example, the timing thread. Before starting a thread, call setDaemon method to convert a thread as a daemon thread. For example: setDaemon (true);

  19. The problem of concurrent execution of multiple threads: multiple threads relative order of execution is uncertain. Thread execution order uncertainty create uncertainty in the results. When multiple threads to shared data operations often generate this uncertainty

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

     21. A method to solve the problem of multi-thread synchronization in Java, there are two: Java SE 5.0 introduced ReentrantLock class. Synchronized modifier was added before the method of shared memory type.

  22. The key points about objects and condition objects locks: locks used to protect code fragment, to ensure that any time only one thread is executing code in protected. Lock Manager thread attempting to enter the protected code segment. Lock may have one or more conditions related objects. Each condition object management thread that has entered the protected code segment but can not run.

  23.synchronized key role: After a certain class methods using synchronized modification, the method is called 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 synchronization method before returning to wake up the thread is blocked, other threads parties may enter synchronization method.

  24. Use wait (), notify and notifyAll () method in the 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 CPU the right to use, and allow other threads to use this synchronization method. If you run out of thread synchronization method should be executed notifyAll () method notifies all due to the use of this method in the thread synchronization wait wait ends

Part II: Experimental part

Experiment 1: Test Procedure 1 (5 min)

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

● grasp the multi-thread synchronization objects and conditions of use lock object implementation.

bank categories:

Package Penalty for Synch; 

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

/ ** 
 * Bank have multiple bank accounts, use the lock to serialize access. 
 * @Version 1.30 2004-08-01 
 * @author Cay Horstmann
  * / 
public  class Bank 
{ 
   Private  Final  Double [] Accounts;
    Private Lock bankLock;
    Private for condition Condition sufficientFunds; 

   / ** 
    * Construction Bank. 
    * @Param number n account 
    * @param initial balance initial balance of each account
     * / 
   publicBank ( int n-, Double initialBalance) 
   { 
      Accounts = new new  Double [n-]; 
      Arrays.fill (Accounts, initialBalance); 
      bankLock = new new of ReentrantLock (); 
      sufficientFunds = bankLock.newCondition (); 
   } 

   / ** 
    * money from a account to another account. 
    * The amount to be transferred from the account to be transferred to the account to be transferred to 
    * / 
   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 total balance
     * / 
   public  Double getTotalBalance () 
   { 
      bankLock.lock (); 
      the try 
      { 
         Double SUM = 0 ; 

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

         return SUM; 
      } 
      the finally 
      { 
         bankLock.unlock (); 
      } 
   } 

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

SynchBankTest categories:

Package Penalty for Synch; 

/ ** 
 * This program shows how multiple threads to safely 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 the 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); 
                  
                  // sleep random 
                  the Thread.sleep (( int ) (the DELAY * Math.random ())); 
               } 
            } 
            the catch (InterruptedException E) 
            { 
            }             
         }; 
         
         // start threads 
         Thread = T new new the Thread (R & lt); 
         t.start (); 
      } 
   } 
}

operation result:

Experiment 1: Test Procedure 2 (5 minutes)

● debug materials 655 program 14-8 in Elipse environment, combined result of the program understand the program;

●  master the synchronized application of multi-thread synchronization.

bank categories:

 

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 初始余额每个帐户的初始余额
    */
   public Bank(int n, double initialBalance)
   {
      accounts = new double[n];
      Arrays.fill(accounts, initialBalance);
      bankLock = new ReentrantLock();
      sufficientFunds = bankLock.newCondition();
   }

   /**
    * 把钱从一个帐户转到另一个帐户。
    *  从要转账的账户到要转账的账户到要转账的金额
    */
   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;
   }
}

 

Synch2BankTest类:

package synch2;

/**
 * 此程序显示多个线程如何使用同步方法安全地访问数据结构。
 * @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();
      }
   }
}

运行结果如下:

 

实验1:测试程序3(5分)

● 在Elipse环境下运行以下程序,结合程序运行结果分析程序存在问题;

● 尝试解决程序中存在问题。

代码如下:

package Thread3;

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,再输出
              s=temp;
              System.out.println("s="+s);
          }
    }


class Customer extends Thread
{
      public void run()
      {
          //连续输出4次
       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)   程序设计思路简述;

创建实现了Runnable接口的类ticket,在ticket类中定义了静态变量i=1以及属性name,在构造器中传入name,将name值赋给this.name;在run方法中判断name的值,根据值的不同来输出不同的东西。

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

ticket类:

package demo;

class ticket implements Runnable{
    private static int num=1;
    private String name;
    public ticket(String name) {
        this.name=name;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        
            
            if(name.equals("0"))
            {
                for(int i=0;i<4;i++)
                {
                    System.out.print("Thread-"+name+"窗口售: 第"+num+"张票\n");
                    num++;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                
            }
            if(name.equals("1"))
            {
                for(int i=0;i<3;i++)
                {
                    System.out.print("Thread-"+name+"窗口售: 第"+num+"张票\n");
                    num++;
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                
            }
            if(name.equals("2"))
            {
                for(int i=0;i<3;i++)
                {
                    System.out.print("Thread-"+name+"窗口售: 第"+num+"张票\n");
                    num++;
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                
                
            }
        
    }
    
}

ticketTest类:

package demo;


public class ticketTest {
     public static void main(String[] args)
     {
         Thread w1=new Thread(new ticket("0"));
         Thread w2=new Thread(new ticket("1"));
         Thread w3=new Thread(new ticket("2"));
         w1.start();
         w2.start();
         w3.start();
     }
}

 

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

 

 实验总结:(5分)

通过本章的学习,我理解和掌握了线程的优先级属性及调度方法,掌握了线程同步的概念及实现技术,可以编写简单的代码来用于解决简单的线程问题了。本次的编程练习对我的启发也很大,让我能够对线程的理解更上一层。

Guess you like

Origin www.cnblogs.com/xiaobeike/p/12077661.html