展开全部
我写了一个例子思路如下 首先定义个公共的list 用户存储插入的记录 开启62616964757a686964616fe4b893e5b19e31333361326238多个线程模拟多人同时插入操作 。在开启一个一个或多个线程处理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
{
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();
}
}