java new Thread()失败_Java Synchronized锁失败案例及解决方案

synchronized关键字,一般称之为”同步锁“,用它来修饰需要同步的方法和需要同步代码块,默认是当前对象作为锁的对象。

同步锁锁的是同一个对象,如果对象发生改变,则锁会不生效。

锁失败的代码:

public class IntegerSynTest {

//线程实现Runnable接口

private static class Worker implements Runnable{

private Integer num;

public Worker(Integer num){

this.num=num;

}

@Override

public void run() {

synchronized (num){

Thread thread = Thread.currentThread();

//System.identityHashCode:返回原生的hashCode值,不管Object对象是被重写;空引用的哈希代码为零

System.out.println(thread.getName()+"--@:---"+System.identityHashCode(num));

num++;

System.out.println(thread.getName()+"------num:"+num+"---"+System.identityHashCode(num));

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(thread.getName()+"------num:"+num+"---"+System.identityHashCode(num));

}

}

public static void main(String[] args) {

Worker worker = new Worker(1);

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

new Thread(worker).start();

}

}

}

}

锁失败的运行结果:

6c65fe8f8b5db15dd0ac7ea5ca5cddba.png

锁失败的原因:

1.num++  的  .class  实现是这样的  Integer integer1 = this.num, integer2 = this.num = Integer.valueOf(this.num.intValue() + 1);

2.查看 Integer.valueOf()的源代码

200666f96e67a2702f4dc2c2db8aead7.png

这时发现,它是重新 new出一个新的Integer,这样的话,每 ++一次,那么就会产生一个新的对象,而Synchronize锁是锁同一个对象,当锁不同对象时,则会锁失败。

解决方法:

Synchronized同步锁只要锁的对象不发生改变即可,那么由此只需要声明一个对象,不修改它,锁这一个对象即可(还有其他方法暂不一一列举,以后也不会列举了)。

锁成功的代码

public class IntegerSynTest {

//线程实现Runnable接口

private static class Worker implements Runnable{

private Integer num;

/**

* ---重点看这里---

* 声明要锁的对象

* ---重点看这里---

*/

private Object object = new Object();

public Worker(Integer num){

this.num=num;

}

@Override

public void run() {

//修改锁对象

synchronized (num){

Thread thread = Thread.currentThread();

//System.identityHashCode:返回原生的hashCode值,不管Object对象是被重写;空引用的哈希代码为零

System.out.println(thread.getName()+"--@:---"+System.identityHashCode(num));

num++;

System.out.println(thread.getName()+"------num:"+num+"---"+System.identityHashCode(num));

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(thread.getName()+"------num:"+num+"---"+System.identityHashCode(num));

}

}

public static void main(String[] args) {

Worker worker = new Worker(1);

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

new Thread(worker).start();

}

}

}

}

锁成功的运行结果:

1b88649624d5e763d1a4be878f5d96d8.png

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值