ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
~~~ public class Provider implements{ //共享缓冲区 private BlockingQueue<Data> queue; //多线程间是否启动的变量,有强制从主存中刷新的功能,即使返回线程状态 private volatile boolean isRunning =true; //id生成器 private static AtomicInteger count =new AtomicInteger(); //随机对象 private static Random r=new Random(); public Provider(BlockingQueue<Data> queue){ this.queue=queue; } public void run(){ while(isRunning){ //随机休眠0-1000ms,表示数据获取 try{ Thread.sleep(r.nextInt(1000)); int id=count.incrementAndGet(); Data data=new Data(Integer.toString(id),"数据"+id); System.out.println("当前线程:"+ Thread.currentThread().getName() + ",获取了数据,id为:"+ id+ ",进行装载到公共缓冲区中。。。"); if(!this.queue.offer(data,2,TimeUnit.SECONDS)){ System.out.print("提交缓冲区数据失败"); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.print("aaa"); } } //用控制变量进行终止 public void stop(){ this.isRunning = false; } ~~~