线程遍历list移除数据

package com.my.module;

import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 线程调用list,
 */
public class Main {

	public static ScheduledExecutorService executors = Executors.newScheduledThreadPool(5);

	/**
	 * 线程安全类
	 * @param args
	 */
	public static void main(String[] args) {

		List<TestData> TestDataList = new CopyOnWriteArrayList<>();

		long now = System.currentTimeMillis();
		TestData testData3 = new TestData("2222222", now + 20000);
		TestData testData1 = new TestData("1111111", now + 1000);
		TestData testData2 = new TestData("2222222", now + 2000);
		TestDataList.add(testData3);
		TestDataList.add(testData1);
		TestDataList.add(testData2);

		new Thread() {
			@Override
			public void run() {

				while (true) {
					try {
						Thread.sleep(500);
						// System.out.println("线程休眠5秒");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					for (TestData testData : TestDataList) {
						// 调用移除方法
						if (testData.getTime() < System.currentTimeMillis()) {
							// 移除掉信息
							TestDataList.remove(testData);
							executors.submit(new MyThread(testData));
						}

					}

				}
			}
		}.start();

		new Thread() {

			@Override
			public void run() {

				while (true) {

					try {
						Thread.sleep(2000);
						System.out.println("线程222休眠2秒");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					int temp = new Random().nextInt(10) + 1;
					TestData testData3 = new TestData(temp + " ", now + 2000);

					TestDataList.add(testData3);
				}

			}

		}.start();

	}

	public static class MyThread extends Thread {

		public TestData testData;

		public MyThread(TestData testData) {
			this.testData = testData;
		}

		@Override
		public void run() {

			try {
				// 模拟线程休眠
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			System.out.println("执行方法 " + testData.getData());

		}

	}

}
package com.my.module;

public class TestData {

	public String data;
	public long time;
	
	public TestData(String data, long time) {
		super();
		this.data = data;
		this.time = time;
	}
	
	public String getData() {
		return data;
	}
	public void setData(String data) {
		this.data = data;
	}
	public long getTime() {
		return time;
	}
	public void setTime(long time) {
		this.time = time;
	}

	@Override
	public String toString() {
		return "TestData [data=" + data + ", time=" + time + "]";
	}

	
	
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值