当前位置:网站首页>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
边栏推荐
- Review of metallurgical physical chemistry --- electrodeposition and reduction process of metals
- 冶金物理化学复习 --- 气-液相反应动力学
- 顺序表oj之删除特定的元素
- SVG了解与绘图应用
- Openjudge: find the first character that appears only once
- IO流的使用
- 三大缓存技术--localStorage、sessionStorage、Cookie
- Advanced multithreading: the role and implementation principle of volatile
- The way of deep learning thermodynamic diagram visualization
- openjudge:万年历
猜你喜欢

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

DOM--事件链、事件冒泡和捕获、事件代理

Idea uses dev tool to realize hot deployment

Sequence table OJ topic

环形链表问题

冶金物理化学复习 --- 液 - 液相反应动力学

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

Centos7 install MySQL 5.7

【uni-app】uni-app中scroll-into-view的使用

DOM——页面的渲染、style属性操作、预加载与懒加载、防抖与节流
随机推荐
【uni-app】uni-app中scroll-into-view的使用
Oracle view lock table statement and unlocking method
ResNet结构对比
Low illumination image data set
The Monte Carlo method solves the PI and draws points with turtle, and completes the progress bar problem
Advanced multi threading: the underlying principle of synchronized, the process of lock optimization and lock upgrade
标准C语言学习总结5
Openjudge: filter extra spaces
Openjudge: stone scissors cloth
DOM——事件
Event_looop-事件循环机制
Docker deploy mysql5.7.35
[singleton mode] thread safety of lazy mode
Delete specific elements in order table OJ
Review of metallurgical physical chemistry -- Fundamentals of chemical reaction kinetics
冶金物理化学复习 --- 气-液相反应动力学
C语言走迷宫
uni-app-双击事件模拟
Openjudge: find the first character that appears only once
顺序表oj题目