Computer >> Máy Tính >  >> Lập trình >> Java

Lỗi can thiệp luồng trong Java

Hãy để chúng tôi xem một ví dụ để hiểu khái niệm về lỗi Giao thoa luồng -

Ví dụ

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

Đầu ra

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

Một lớp có tên là ‘Demo_instance’ xác định một giá trị tĩnh và một hàm void ‘increment_val’, biến đổi trên một tập hợp các số và tăng dần nó lên và hiển thị trên bảng điều khiển. Một chức năng khác có tên là ‘decment_val’ lặp lại trên một tập hợp các số và số giảm mỗi lần và hiển thị thông lượng trên bảng điều khiển.

Một lớp có tên Demo chứa hàm chính tạo ra một thể hiện của lớp và tạo luồng mới. Luồng này bị ghi đè và hàm run được gọi trên cá thể đối tượng này. Điều tương tự cũng được thực hiện cho chủ đề thứ hai. Sau đó, cả hai luồng này được gọi bằng hàm "start".