Java 中的執行緒干擾錯誤


我們看一個示例,以瞭解執行緒干擾錯誤的概念:

示例

 即時演示

import java.io.*;
class Demo_instance{
   static int val_1 = 6;
   void increment_val(){
      for(int j=1;j<11;j++){
         val_1 = val_1 + 1;
         System.out.println("The value of i after incrementing it is "+val_1);
      }
   }
   void decrement_val(){
      for(int j=1;j<11;j++){
         val_1 = val_1 - 1;
         System.out.println("The value of i after decrementing it is "+val_1);
      }
   }
}
public class Demo{
   public static void main(String[] args){
      System.out.println("Instance of Demo_instance created");
      System.out.println("Thread instance created");
      final Demo_instance my_inst = new Demo_instance();
      Thread my_thread_1 = new Thread(){
         @Override
         public void run(){
            my_inst.increment_val();
         }
      };
      Thread my_thread_2 = new Thread(){
         @Override
         public void run(){
            my_inst.decrement_val();
         }
      };
      my_thread_1.start();
      my_thread_2.start();
   }
}

輸出

Instance of Demo_instance created
Thread instance created
The value of i after incrementing it is 7
The value of i after incrementing it is 7
The value of i after decrementing it is 6
The value of i after incrementing it is 8
The value of i after decrementing it is 7
The value of i after incrementing it is 8
The value of i after incrementing it is 8
The value of i after decrementing it is 7
The value of i after incrementing it is 9
The value of i after decrementing it is 8
The value of i after decrementing it is 7
The value of i after decrementing it is 6
The value of i after decrementing it is 5
The value of i after decrementing it is 4
The value of i after decrementing it is 3
The value of i after decrementing it is 2
The value of i after incrementing it is 3
The value of i after incrementing it is 4
The value of i after incrementing it is 5
The value of i after incrementing it is 6

類“Demo_instance”定義了一個靜態值,和一個 void 函式“increment_val”,它會遍歷一組數字,並對其進行遞增並在控制檯上顯示。另一個名為“decrement_val”的函式會遍歷一組數字,並每次進行遞減並在控制檯上顯示輸出。

類 Demo 包含一個主函式,該函式建立類的例項,並建立一個新執行緒。該執行緒已被重寫,run 函式呼叫此物件例項。對於第二個執行緒,也執行了相同操作。這兩個執行緒隨後會被 start 函式呼叫。

更新於:2020 年 7 月 14 日

147 次瀏覽

開啟你的職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.