java使用map实现锁,java hashmap分段锁实现

该博客探讨了在Java中如何使用多线程对HashMap进行同步操作。通过创建两个线程,分别更新键为'1'和'2'的值,展示了`synchronized`关键字的使用来保证线程安全。同时,展示了在迭代HashMap时如何避免并发修改异常。
摘要由CSDN通过智能技术生成

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;public classTestThred03 extends Thread {private static int num = 0;private static int num1 = 0;private static HashMap hashMap = new HashMap();publicTestThred03() {

num= 0;

num1=0;

hashMap.put("1", 0);

hashMap.put("2", 0);

hashMap.put("3", 0);

hashMap.put("4", 0);

hashMap.put("5", 0);

}public voidrun() {

Iterator iter=hashMap.entrySet().iterator();while(iter.hasNext()) {

Map.Entry entry=(Map.Entry) iter.next();

Object key=entry.getKey();

Object val=entry.getValue();if (key.equals("1") || key.equals("2")) {

synchronized (this) {

num++;

entry.setValue(num);

System.out.println(Thread.currentThread().getName()+"-num:"+num);try{

Thread.sleep(100);

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}else{

synchronized (this) {

num1++;

entry.setValue(num1);

System.out.println(Thread.currentThread().getName()+"-num1:"+num1);try{

Thread.sleep(100);

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}

}

}public static voidmain(String[] args) {

TestThred03 syncThread= newTestThred03();

Thread thread1= new Thread(syncThread, "SyncThread1");

Thread thread2= new Thread(syncThread, "SyncThread2");

thread1.start();

thread2.start();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值