java有很多人同时进行插入操作, 有没有例子,先全部扔一个集合里面, 然后一起进行批量的提交。
答案:1 悬赏:0
解决时间 2021-01-11 18:24
- 提问者网友:你给我的爱
- 2021-01-11 05:39
java有很多人同时进行插入操作, 有没有例子,先全部扔一个集合里面, 然后一起进行批量的提交。
最佳答案
- 二级知识专家网友:一叶十三刺
- 2021-01-11 06:48
我写了一个例子思路如下 首先定义个公共的list 用户存储插入的记录 开启多个线程模拟多人同时插入操作 。在开启一个一个或多个线程处理list中数据代码如下
package com.zhidao20161208;
import java.util.concurrent.ConcurrentLinkedQueue;
public class BeanOne extends Thread {
public static ConcurrentLinkedQueue list = new ConcurrentLinkedQueue();// 定义公共的list
// 此处使用ConcurrentLinkedQueue为线程安全队列
public void run() {
while (true) {
String str = list.poll();// 每次弹出一个元素遵循先入先出的原则
System.out.println(str);
}
}
}package com.zhidao20161208;
public class ThreadA extends Thread {
private String str;
public ThreadA(String str) {
this.str = str;
}
public void run() {
int i = 1;
while (true) { // 模拟插入操作,此处为死循环每开启一个线程则认为一个人在做插入操作
try {
BeanOne.list.add(str + i);// 写入ConcurrentLinkedQueue(线程安全的队列可以支持多线程)
} catch (Exception e) {
e.printStackTrace();
}
i++;
}
}
}package com.zhidao20161208;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < 3; i++)// 开启多线程模拟多人同时操作
{
ThreadA threadA = new ThreadA(null);
if (i == 0) {
threadA = new ThreadA("ThreadA");
}
if (i == 1) {
threadA = new ThreadA("ThreadB");
}
if (i == 2) {
threadA = new ThreadA("ThreadC");
}
threadA.start();
}
BeanOne threadB = new BeanOne();// 启动输出线程
threadB.start();
}
}
package com.zhidao20161208;
import java.util.concurrent.ConcurrentLinkedQueue;
public class BeanOne extends Thread {
public static ConcurrentLinkedQueue
// 此处使用ConcurrentLinkedQueue为线程安全队列
public void run() {
while (true) {
String str = list.poll();// 每次弹出一个元素遵循先入先出的原则
System.out.println(str);
}
}
}package com.zhidao20161208;
public class ThreadA extends Thread {
private String str;
public ThreadA(String str) {
this.str = str;
}
public void run() {
int i = 1;
while (true) { // 模拟插入操作,此处为死循环每开启一个线程则认为一个人在做插入操作
try {
BeanOne.list.add(str + i);// 写入ConcurrentLinkedQueue(线程安全的队列可以支持多线程)
} catch (Exception e) {
e.printStackTrace();
}
i++;
}
}
}package com.zhidao20161208;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < 3; i++)// 开启多线程模拟多人同时操作
{
ThreadA threadA = new ThreadA(null);
if (i == 0) {
threadA = new ThreadA("ThreadA");
}
if (i == 1) {
threadA = new ThreadA("ThreadB");
}
if (i == 2) {
threadA = new ThreadA("ThreadC");
}
threadA.start();
}
BeanOne threadB = new BeanOne();// 启动输出线程
threadB.start();
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息