创建大量线程发送数据,list报错发送任务(标签),接收返回任务(标签),循环list标签配对,返回状态,超时结束任务 。如简图
需要自己整理一下,项目只提供思路
main.Java
import java.util.ArrayList;
public class ceshi {
static ArrayList<WriteHelp> list = new ArrayList<>();
public static void main(String[] args) {
// ComProtocolPresenter.getInstance();//初始化
创建一个数据集合
for (int i = 0; i < 10000; i++) {
WriteHelp writeHelp = new WriteHelp();
byte[] bytes = new byte[1024];
writeHelp.send("CS" + i, bytes);
writeHelp.setResult(new Callback() {
@Override
public void success() {
System.out.println("发送成功");
}
@Override
public void failed() {
System.out.println("失败");
}
@Override
public void timeOut() {
System.out.println("超时");
}
@Override
public void error(Exception e) {
System.out.println("错误:" + e.getMessage());
}
});
addElement(writeHelp);
//ComProtocolPresenter.getInstance().onDataDifferent(writeHelp);
}
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("启动时间:" + System.currentTimeMillis());
for (int i = 0; i < 10000; i++) {
try {
Thread.sleep(5);
runbe("CS" + i);
//string1 = "CS" + i;
//ComProtocolPresenter.getInstance().setString("CS" + i);
//System.out.println(ComProtocolPresenter.getInstance().string);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("结束时间:" + System.currentTimeMillis());
}
}).start();
///清理超时
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
WriteHelp help = list.get(i);
// System.out.println("当前" + string +" -- "+ help.getTile1());
try {
// if (!help.getBool()) {
// removeElement(help);
// break;
// }
if (help.setTimeOut()) {
if (help.getResult() != null) help.getResult().timeOut();
// help.setBool(false);
removeElement(help);
// break;///跳出for循环
}
} catch (Exception e) {
if (help.getResult() != null) help.getResult().error(e);
}
}
}else{
System.out.println("结束循环");
return;
}
}
}
}).start();
}
public static void addElement(WriteHelp element) {
synchronized (list) {
list.add(element);
}
}
public static boolean removeElement(WriteHelp index) {
synchronized (list) {
return list.remove(index);
}
}
///收到一个消息就创建一个线程
public static void runbe(String str) {
new Thread(new Runnable() {
@Override
public void run() {
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
WriteHelp help = list.get(i);
try {
if (help.getTile1().equals(str)) {
if (help.getResult() != null) help.getResult().success();
//help.setBool(false);
removeElement(help);
System.out.println("成功!----------" + help.getTile1());
return;
}
} catch (Exception e) {
if (help.getResult() != null) help.getResult().error(e);
}
}
}
}
}).start();
}
}
WriteHelp.kt
//执行指令
class WriteHelp {
///开始时间
private val lastTime = System.currentTimeMillis()
val TIME_OUT_DURATION = 89890//超时时限,默认1500,特殊的需要可改变该值
private var max = 2
private val mType = 1
var bool1: Boolean = true
fun getBool(): Boolean {
return bool1
}
///超时
fun setTimeOut(): Boolean {
return System.currentTimeMillis() - lastTime > TIME_OUT_DURATION
}
fun setBool(bool1: Boolean) {
this.bool1 = bool1
}
private var result: Callback? = null
fun getResult(): Callback? {
return result
}
fun setResult(result: Callback?) {
this.result = result
}
fun getType(): Int {
return mType
}
fun getTimeOutDuration(): Long {
return TIME_OUT_DURATION.toLong()
}
fun getMax(): Int {
return max
}
fun setMax(max: Int) {
this.max = max
}
///判断对应键值对 是对应消息
var tile1: String = ""
//发送的
var sendData1: ByteArray? = null
//接收的
var receiveData1: ByteArray? = null
fun send(tile: String, sendData: ByteArray) {
this.tile1 = tile
this.sendData1 = sendData
}
}
Callback 回调接口
interface Callback {
//成功
fun success() {
}
//失败
fun failed() {
}
//超时
fun timeOut() {
}
//错误内容
fun error(e: Exception) {
}
}
非常重要的地方 提供一个小案例
在Java中,当多个线程同时操作ArrayList时,可能会出现并发修改异常(ConcurrentModificationException)。这是因为ArrayList是非线程安全的,如果多个线程同时对其进行修改,可能会导致不一致的结果。
为了避免这种情况,可以使用线程安全的集合类,如Vector或CopyOnWriteArrayList。或者,可以使用同步块(synchronized block)来确保在任何时候只有一个线程可以访问ArrayList。
以下是使用同步块保护ArrayList的示例:
List<String> list = new ArrayList<>();
public void addElement(String element) {
synchronized (list) {
list.add(element);
}
}
public String removeElement(int index) {
synchronized (list) {
return list.remove(index);
}
}
在上述示例中,addElement()和removeElement()方法都使用了同步块来保护对ArrayList的访问。这样可以确保在任何时候只有一个线程可以修改列表,从而避免并发修改异常。