java i 线程不安全_Java 线程不安全问题分析

当多个线程并发访问同一个资源对象时,可能会出现线程不安全的问题

b5523916eb4935538f0ce488cdc8a7c1.png

f78169b4cedf457034386ef7557c2b7d.png

public class Method implements Runnable {

private static int num=50;

public void run() {

for(int i=0;i<50;i++){

eat();

}

}

synchronized private void eat(){

if(num>0){

System.out.println(Thread.currentThread().getName()+"吃了编号为"+num+"的苹果!");

try {

Thread.sleep(10);

} catch (InterruptedException e) {

e.printStackTrace();

}

num--;

}

}

public static void main(String[] args) {

Thread t=new Thread();

Method a=new Method();

new Thread(a,"小A").start();

new Thread(a,"小B").start();

new Thread(a,"小C").start();

}

}

public class Method_1 implements Runnable {

private static int num = 50;

public void run() {

for (int i = 0; i < 50; i++) {

synchronized (this) {

if (num > 0) {

System.out.println(Thread.currentThread().getName() + "吃了编号为" + num + "的苹果!");

try {

Thread.sleep(10);

} catch (InterruptedException e) {

e.printStackTrace();

}

num--;

}

}

}

}

public static void main(String[] args) {

Method_1 m = new Method_1();

new Thread(m, "小A").start();

;

new Thread(m, "小B").start();

;

new Thread(m, "小C").start();

;

}

}

31543589ca90c3d63bd40cd9d4998ca7.png

c53f512b8d4054409150fd22bfeae1f8.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值