ROS中的Hyperframes超帧:多传感器时间同步与坐标对齐实战指南
2026/10/29 14:30:30
章节目录
publicclassExitFlagTests{// volatile修饰符用来保证其它线程读取的总是该变量的最新的值privatevolatilebooleanexitFlag=false;// 退出标志publicvoidrun(){while(!exitFlag){// 执行线程的任务System.out.println("Thread is running...");try{Thread.sleep(1000);// 模拟一些工作}catch(InterruptedExceptione){// 处理中断(如果需要)Thread.currentThread().interrupt();// 重新设置中断状态}}System.out.println("Thread is stopping...");}publicvoidstop(){exitFlag=true;// 设置退出标志为true}publicstaticvoidmain(String[]args)throwsInterruptedException{ExitFlagTestsexit=newExitFlagTests();Threadthread=newThread(exit::run);thread.start();// 让线程运行一段时间Thread.sleep(5000);// 请求线程停止exit.stop();}}publicclassStopMethodTestsextendsThread{publicvoidrun(){while(true){System.out.println("Thread is running...");try{Thread.sleep(1000);}catch(InterruptedExceptione){Thread.currentThread().interrupt();}}}publicstaticvoidmain(String[]args)throwsInterruptedException{StopMethodTeststhread=newStopMethodTests();thread.start();// 让线程运行一段时间Thread.sleep(5000);// 强行中止线程(不推荐)thread.stop();}}为什么启用stop:
publicclassInterruptTestsextendsThread{publicstaticvoidmain(String[]args){try{InterruptTestst=newInterruptTests();// 启动线程t.start();Thread.sleep(200);// 中断线程 tt.interrupt();}catch(InterruptedExceptione){e.printStackTrace();}}@Overridepublicvoidrun(){super.run();// 循环打印 i 的值,从 0 到 200000for(inti=0;i<=200000;i++){System.out.println("i="+i);}}}通过运行以上代码,我们会发现interrupt方法并没有停止线程t中的处理逻辑,也就是说t线程被设置中断状态,但这个中断不会起作用,那么如何停止线程呢?
publicbooleanThread.isInterrupted()//判断是否被中断publicstaticbooleanThread.interrupted()//判断是否被中断,并清除当前中断状态这两个方法使得当前线程能够感知到是否被中断了(通过检查标志位)。
所以如果希望线程 t 在中断后停止,就必须先判断是否被中断,并为它增加相应的中断处理代码:
@Overridepublicvoidrun(){super.run();for(inti=0;i<=200000;i++){//判断是否被中断if(Thread.currentThread().isInterrupted()){//处理中断逻辑break;}System.out.println("i="+i);}}在上面这段代码中,我们增加了 Thread.isInterrupted() 来判断当前线程是否被中断了,如果是,则退出 for 循环,结束线程。
这种方式看起来与之前介绍的“使用标志位中止线程”非常类似,但是在遇到 sleep() 或者 wait() 这样的操作,我们只能通过中断来处理了。
publicstaticnativevoidsleep(longmillis)throwsInterruptedException[!NOTE]
(注意:Thread.sleep() 方法由于中断而抛出的异常,是会清除中断标记的。)