1. 程式人生 > >達拉草201771010105《面向物件程式設計(java)》第十七週學習總結

達拉草201771010105《面向物件程式設計(java)》第十七週學習總結

達拉草201771010105《面向物件程式設計(java)》第十七週學習總結

第一部分:理論知識

1.多執行緒的概念:

(1)多執行緒是程序執行過程中產生的多條執行線索。 

(2)多執行緒意味著一個程式的多行語句可以看上去幾 乎在同一時間內同時執行。 

(3)執行緒不能獨立存在,必須存在於程序中,同一進 程的各執行緒間共享程序空間的資料。 

Java實現多執行緒有兩種途徑:
建立Thread類的子類
在程式中定義實現Runnable介面的類

用Thread類的子類建立執行緒:

(1)首先需從Thread類派生出一個子類,在該子類中 重寫run()方法。 

例: class hand extends Thread {

public void run() {……}

}

(2) 然後用建立該子類的物件 

Lefthand left=new Lefthand();

Righthand right=new Righthand(); 

(3)最後用start()方法啟動執行緒 

left.start();

right.start();

用Thread類的子類建立多執行緒的關鍵性操作:

(1)定義Thread類的子類並實現使用者執行緒操作,即 run()方法的實現。

(2)在適當的時候啟動執行緒。

由於Java只支援單重繼承,用這種方法定義的類不 可再繼承其他父類。

用Runnable()介面實現執行緒

(1)首先設計一個實現Runnable介面的類; 

(2) 然後在類中根據需要重寫run方法; 

(3)再建立該類物件,以此物件為引數建立Thread 類的物件; 

(4)呼叫Thread類物件的start方法啟動執行緒,將 CPU執行權轉交到run方法。

被阻塞執行緒和等待執行緒

 blocked (被阻塞):

阻塞時執行緒不能進入佇列排隊,必須等到引起 阻塞的原因消除,才可重新進入排隊佇列。 

sleep(),wait()是兩個常用引起執行緒阻塞的方法。

執行緒阻塞的三種情況:

(1)等待阻塞 :通過呼叫執行緒的wait()方法,讓線 程等待某工作的完成。 

(2)同步阻塞 :執行緒在獲取synchronized同步鎖失 敗(因為鎖被其它執行緒所佔用),它會進入同步阻 塞狀態。 

(3)其他阻塞 :通過呼叫執行緒的sleep()或join() 或發出了I/O請求時,執行緒會進入到阻塞狀態。當 sleep()狀態超時、join()等待執行緒終止或者超 時、或者I/O處理完畢時,執行緒重新轉入就緒狀態。

被終止的執行緒

 Terminated (被終止) 執行緒被終止的原因有二: 

(1)一是run()方法中最後一個語句執行完畢而自 然死亡。 

(2)二是因為一個沒有捕獲的異常終止了run方法 而意外死亡。 

可以呼叫執行緒的stop 方 法 殺 死 一 個 線 程 (thread.stop();),但是,stop方法已過時, 不要在自己的程式碼中呼叫它。

其他判斷和影響執行緒狀態的方法:

(1)join():等待指定執行緒的終止。 

(2)join(long millis):經過指定時間等待終止指定 的執行緒。 

(3)isAlive():測試當前執行緒是否在活動。 

(4)yield():讓當前執行緒由“執行狀態”進入到“就 緒狀態”,從而讓其它具有相同優先順序的等待執行緒 獲取執行權。

多執行緒排程

(1)Java提供一個執行緒排程器來監控程式啟動後進入可執行狀態的所有執行緒。執行緒排程器按照執行緒的優先順序決定應排程哪些執行緒來執行。

(2)處於可執行狀態的執行緒首先進入就緒佇列排隊等候處理器資源,同一時刻在就緒佇列中的執行緒可能有多個。Java的多執行緒系統會給每個執行緒自動分配一個執行緒的優先順序。

 Java 的執行緒排程採用優先順序策略:

(1)優先順序高的先執行,優先順序低的後執行;

(2)多執行緒系統會自動為每個執行緒分配一個優先順序,預設時,繼承其父類的優先順序;

(3)任務緊急的執行緒,其優先順序較高;

(4)同優先順序的執行緒按“先進先出”的佇列原則;

守護執行緒

守護執行緒的惟一用途是為其他執行緒提供服務。例 如計時執行緒。

在一個執行緒啟動之前,呼叫setDaemon方法可 將執行緒轉換為守護執行緒(daemon thread)。 例如: setDaemon(true);

 

實驗十七  執行緒同步控制

實驗時間 2018-12-10

1、實驗目的與要求

(1) 掌握執行緒同步的概念及實現技術;

(2) 執行緒綜合程式設計練習

2、實驗內容和步驟

實驗1:測試程式並進行程式碼註釋。

測試程式1:

l  在Elipse環境下除錯教材651頁程式14-7,結合程式執行結果理解程式;

l  掌握利用鎖物件和條件物件實現的多執行緒同步技術。

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 = new ReentrantLock();
      sufficientFunds = bankLock.newCondition();
   }

   /**
    * Transfers money from one account to another.
    * @param from the account to transfer from
    * @param to the account to transfer to
    * @param amount the amount to transfer
    */
   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();//釋放鎖
      }
   }

   /**
    * Gets the sum of all account balances.
    * @return the total balance
    */
   public double getTotalBalance()
   {
      bankLock.lock();
      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;
   }
}
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();
      }
   }
}

執行結果如下:

測試程式2:

l  在Elipse環境下除錯教材655頁程式14-8,結合程式執行結果理解程式;

l  掌握synchronized在多執行緒同步中的應用。

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.
    * @param from the account to transfer from
    * @param to the account to transfer to
    * @param amount the amount to transfer
    */
   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();
   }

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

執行結果如下:

測試程式3:

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

  }

}

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 程式設計練習

利用多執行緒及同步方法,編寫一個程式模擬火車票售票系統,共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張票

 

public class Demo {
    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();
}
}
class mythread implements Runnable{
    int t=1;
    boolean flag=true;
    @Override
    public void run() {
        while(flag) {
            try {
                Thread.sleep(50);
            }catch(InterruptedException e)
            {
                e.printStackTrace();
            }
            synchronized (this) {
            if(t<=10) {
        // TODO Auto-generated method stub
                 System.out.println(Thread.currentThread().getName() + "視窗售:第" + t + "張票");
                 t++;
            }
            if(t>10) {
                flag=false;
            }
            }
        }
    
    }
    
}

執行結果如下:

實驗總結:

       本週學習了同步執行緒的相關問題,這也是我們最後一次實驗,在這周的學習中我們學習了併發多執行緒,學習了鎖物件、synchronized關鍵字等。