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”的类定义了一个静态值,以及一个无效函数“increment_val”,该函数遍历一组数字,并将其递增并显示在控制台上。另一个名为“decrement_val”的函数每次都会迭代一组数字和减量,并在控制台上显示输出。
名为Demo的类包含创建该类实例并创建新线程的主要功能。重写此线程,并在此对象实例上调用run函数。第二个线程也做同样的事情。然后使用“开始”功能调用这两个线程。