201271050130- Teng Jiangnan - "object-oriented programming (java)" Week 17 learning summary

201271050130- Teng Jiangnan - "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)

1, the thread termination

- When the body after execution method 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.

- calling interrupt () method can terminate the thread.

void interrupt()

- Send a thread to an interrupt request, while the "interrupted" state of this thread is set to true.

- If the thread is blocked state, it will throw InterruptedException.

2, whether the test was interrupted thread method

Java provides several methods used to test whether the thread is interrupted.

-static boolean interrupted()

- detect whether the current thread has been interrupted and reset state "interrupted" is false. 

-boolean isInterrupted()

- detect whether the current thread has been interrupted, does not change the state "interrupted" value.

State 3, thread

- use of state transition of each thread, each thread can be controlled using the CPU in turn, reflect the characteristics of multi-threaded parallelism. 

- thread has the following seven states:

➢ New (New)

➢ Runnable (run)

➢ Running (running)

➢ Blocked (blocked)

➢ Waiting (waiting)

➢ Timed waiting (waiting timer)

➢ Terminated (terminated)

4. Create a new thread

-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.

5, runnable threads

- runnable (runnable)

➢ thread has been started at this time, among the methods in the thread run ().

➢ threads may be running at this time, or may not run as long as a CPU is idle, it will soon run.

➢ calling thread's start () method allows the thread is "runnable" state. For example: thread.start ();

6, and the thread is blocked waiting threads

- blocked (blocked)

➢ a thread being executed due to special reasons, be suspended into the blocked state.

➢ When blocked thread can not enter the queue line up, must wait until the causes obstruction to eliminate before they can re-enter the queue line.

➢ obstruction caused by many reasons, different reasons to use different methods to lift.

-sleep (), wait () method is commonly caused by two threads blocked.

7, thread blocked three cases

- Wait blocking - by calling the thread wait () method, thread to wait for the completion of a job.

- synchronous blocking - a thread get synchronized synchronous lock failure (because the lock was occupied by another thread), it will enter synchronous blocking state.

- Other blocked - by 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.

8, was terminated thread

There are two reasons Terminated (terminated) thread is terminated:

➢ First run () method in the last statement is finished and died of natural causes.

➢ a second, because there is no capture of aborted the run method and accidental death.

➢ thread can call the stop method to kill a thread (thread.stop ();), however, stop method is obsolete and do not call it in your own code.

9, multi-thread scheduling

-Java thread scheduling uses priority policies:

➢ high priority to the implementation, lower priority after execution;

➢ multi-threaded system will automatically assign a priority to each thread, by default, inherit its parent's priority;

➢ mission-critical threads, the higher priority;

➢ the same priority thread by "FIFO" queue principle;

10, Thread class has three static and thread priorities related to the amount of:

➢ MAX_PRIORITY: the highest priority, is 10;

➢ MIN_PRIORITY: minimum priority value is 1;

➢ NORM _PRIORITY: default priority value is 5.

 Java thread scheduling uses priority policies: first implementation of high-priority, low priority after execution; a multi-threaded system will automatically assign a priority to each thread, by default, inherit its parent's priority; task emergency threads, the higher the priority; the same priority thread queue according to the principle "first in first out" of.

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.

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: J ava SE 5.0 introduced ReentrantLock class. Synchronized modifier was added before the method of shared memory type.

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.

synchronized keyword role: within a class method with the 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 returns from before synchronization method wake thread is blocked, other threads parties may enter synchronization method.

Use wait (), notify and notifyAll () in synchronization method method: 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.

Part II: Experimental part

Experiment 1: Test Procedure 1 (5 min)

Test Procedure 1:

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.

Synch Package Penalty for; 

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

/ * * 
a bank account there are many banks, using locks 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 n account 
    * @param initialBalance initial balance for each account 
    * / 
   public Bank ( int n-, Double initialBalance) 
   { 
      Accounts = new new  Double [n-]; 
      Arrays.fill (Accounts, initialBalance); 
      bankLock = new new of ReentrantLock (); 
      sufficientFunds = bankLock.newCondition (); 
   } 

   / * * 
    * 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 ();
       the 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 (); 
      } 
      the finally 
      }
      { 
         BankLock.unlock (); 
      } 
   } 

   / * * 
    * Get the sum of all of the account balance. 
    * @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 ();
   } 

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

 

Synch Package Penalty for; 

/ * * 
 * This program shows how to safely multiple threads access the data structure. 
 2015-06-21 @version 1.31 * 
 * @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);
                  Thread.sleep((int) (DELAY * Math.random()));
               }
            }
            catch (InterruptedException e)
            {
            }            
         };
         Thread t = new Thread(r);
         t.start();
      }
   }
}

operation result:

 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.

package synch2;

import java.util.*;

/**
 * 具有多个使用同步原语的银行账户的银行。
 * @version 1.30 2004-08-01
 * @author Cay Horstmann
 */
public class Bank
{
   private final double[] accounts;

   /**
    * 建设银行。
    * @param n 账号
    * @param initialBalance 每个账户的初始余额
    */
   public Bank(int n, double initialBalance)
   {
      accounts = new double[n];
      Arrays.fill(accounts, initialBalance);
   }

   /**
    * 把钱从一个账户转到另一个账户。
    * @param 从账户转账
    * @param 转到要转账的账户
    * @param 请允许我向你转达
    */
   public synchronized void transfer(int from, int to, double amount) throws InterruptedException
   {
      while (accounts[from] < amount)
         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();
   }

   /**
    * 获取所有帐户余额的总和。
    * @return 总余额
    */
   public synchronized double getTotalBalance()
   {
      double sum = 0;

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

      return sum;
   }

   /**
    * 获取银行中的帐户数量。
    * @return 
    */
   public int size()
   {
      return accounts.length;
   }
}

 

package synch2;

import java.util.*;

/**
 * 具有多个使用同步原语的银行账户的银行。
 * @version 1.30 2004-08-01
 * @author Cay Horstmann
 */
public class Bank
{
   private final double[] accounts;

   /**
    * 建设银行。
    * @param n 账号
    * @param initialBalance 每个账户的初始余额
    */
   public Bank(int n, double initialBalance)
   {
      accounts = new double[n];
      Arrays.fill(accounts, initialBalance);
   }

   /**
    * 把钱从一个账户转到另一个账户。
    * @param 从账户转账
    * @param 转到要转账的账户
    * @param 请允许我向你转达
    */
   public synchronized void transfer(int from, int to, double amount) throws InterruptedException
   {
      while (accounts[from] < amount)
         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();
   }

   /**
    * 获取所有帐户余额的总和。
    * @return 总余额
    */
   public synchronized double getTotalBalance()
   {
      double sum = 0;

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

      return sum;
   }

   /**
    * 获取银行中的帐户数量。
    * @return 
    */
   public int size()
   {
      return accounts.length;
   }
}

  运行结果:

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

运行结果:

改进:

package sdfsd;

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)   程序运行功能界面截图;

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);
        ticket1.start();
        ticket2.start();
        ticket3.start();
    }
}

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

}

运行结果:

实验总结:(5分)

       在本周的学习中,我学习了线程同步这一知识点,我了解到这一知识点是用来解决多线程并发运行不确定性问题。了解了并发多线程的两种解决方法,一种是锁对象,还有一种是synchronized关键字。还有wait()、notify 和notifyAll()方法。 这学期Java课程已经结束了,在学习过程中感谢代老师认真负责传授知识,助教耐心帮带,非常感谢。

Guess you like

Origin www.cnblogs.com/tjnkxh/p/12074791.html