当前位置:网站首页>ArrayList multithreading security solution
ArrayList multithreading security solution
2022-07-28 05:44:00 【Little madman green】
Tested to solve thread safety problems
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();
// }
}
}
}
}
Running results :
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
边栏推荐
- 标准C语言总结2
- JUC notes
- The Monte Carlo method solves the PI and draws points with turtle, and completes the progress bar problem
- openjudge:找出全部子串位置
- Example of main diagram of paper model
- Event_looop-事件循环机制
- Image enhancement - msrcr
- Implementation of date class and its basic functions
- Review of metallurgical physical chemistry --- liquid liquid reaction kinetics
- 顺序表oj之合并两个有序数组
猜你喜欢

冶金物理化学复习 --- 化学反应动力学基础

Review of Metallurgical Physical Chemistry - gas liquid phase reaction kinetics

Mutual conversion between latex and word

冶金物理化学复习 ---- 气固反应动力学

顺序表的增删查改

Using Navicat or PLSQL to export CSV format, more than 15 digits will become 000 (e+19) later

Custom JSON return data

The Monte Carlo method solves the PI and draws points with turtle, and completes the progress bar problem

JUC notes

DOM——页面的渲染、style属性操作、预加载与懒加载、防抖与节流
随机推荐
顺序表的增删查改
C语言推箱子
URL 形式
Sequence table OJ topic
js数据类型检测与修改检测
openjudge:过滤多余的空格
Pytorch uses hook to get feature map
Oracle uses SQL to query the field information of a table (field type, length, etc.)
博学谷学习记录】超强总结,用心分享 | 常用api
openjudge:校园食宿预订系统
ResNet结构对比
Review of metallurgical physical chemistry --- liquid liquid reaction kinetics
C语言回顾(字节对齐篇)
openjudge:万年历
openjudge:矩阵乘法
三大缓存技术--localStorage、sessionStorage、Cookie
Use of IO streams
Merge two ordered arrays of order table OJ
GET与POST区别
Review of metallurgical physical chemistry -- cathodic polarization, overpotential, anode and anode process in metal electrodeposition