当前位置:网站首页>ArrayList多线程安全解决办法
ArrayList多线程安全解决办法
2022-07-28 05:16:00 【小疯子青】
经测试可以解决线程安全问题
public class Main {
public static volatile Boolean flag = false;
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
for (int i = 0; i < 100; i++) {
arrayList.add(Integer.toString(i));
}
Iterator i = arrayList.listIterator();
for (int x = 0; x < 100; x++) {
MyThread myThread = new MyThread(i, arrayList);
myThread.start();
}
flag = true;
}
static class MyThread extends Thread {
private Iterator i;
private ArrayList arrayList;
public MyThread(Iterator i, ArrayList arrayList) {
this.i = i;
this.arrayList = arrayList;
}
@Override
public void run() {
while (!flag) {
}
while (i.hasNext()) {
synchronized (flag) {
if (i.hasNext()) {
Object o = i.next();
System.out.println(currentThread().getName() + ":" + o + ":" + o.hashCode());
i.remove();
}
}
// try {
// sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
}
}
运行结果:
Thread-59:89:1793
Thread-55:90:1815
Thread-63:91:1816
Thread-70:92:1817
Thread-75:93:1818
Thread-71:94:1819
Thread-74:95:1820
Thread-79:96:1821
Thread-83:97:1822
Thread-82:98:1823
Thread-86:99:1824
Process finished with exit code 0
边栏推荐
- HDU 2874 connections between cities
- Pipe /createpipe
- Autoreleasepool problem summary
- Specific differences between typedef and define
- The solution after the samesite by default cookies of Chrome browser 91 version are removed, and the solution that cross domain post requests in chrome cannot carry cookies
- 类和对象【中】
- HDU 1530 maximum clique
- 在外包公司两年了,感觉快要废了
- Gan: generative advantageous nets -- paper analysis and the mathematical concepts behind it
- php7.1 连接sqlserver2008r2 如何测试成功
猜你喜欢

How to send and receive reports through outlook in FastReport VCL?

Online sql to XML tool

RT based_ Distributed wireless temperature monitoring system based on thread

From the basic concept of micro services to core components - explain and analyze through an example

Check box error

FreeRTOS learning (I)

这种动态规划你见过吗——状态机动态规划之股票问题(中)

PC端-bug记录

【ARXIV2203】SepViT: Separable Vision Transformer

Reading notes of SMT practical guide 1
随机推荐
regular expression
Gym 101911c bacteria (minimum stack)
Dell remote control card uses ipmitools to set IPMI
数据安全逐步落地,必须紧盯泄露源头
PC端-bug记录
Configuration experiment of building virtual private network based on MPLS
Gan: generative advantageous nets -- paper analysis and the mathematical concepts behind it
面试了一位38岁程序员,听说要加班就拒绝了
测试开发---自动化测试中的UI测试
Flask Development & get/post request
Win10 machine learning environment construction pycharm, anaconda, pytorch
Supervisor series: 5. Log
Check box error
阿里怎么用DDD来拆分微服务?
Reading sdwebimage source code Notes
New arrow function in ES6
C language: addition and deletion of linked list in structure
How to simulate common web application operations when using testcafe
Barbie q! How to analyze the new game app?
list indices must be integers or slices, not tuple