java 线程错误_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函数。第二个线程也做同样的事情。然后使用“开始”功能调用这两个线程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值