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 次浏览

开启你的职业生涯

通过完成课程来获得认证

开始
广告