Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Lỗi can thiệp luồng (Thread Interference Error) trong Java


Xem ví dụ để hiểu khái niệm lỗi can thiệp 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();    } }

Kết quả

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

Lớp Demo_instance định nghĩa giá trị static và hàm void increment_val lặp qua tập số, tăng và in ra. Hàm decrement_val lặp và giảm. Lớp Demo chứa main tạo thể hiện lớp, tạo luồng mới, ghi đè và gọi run. Cùng làm cho luồng thứ hai. Cả hai luồng được gọi bằng start.