public static void testThreadState() { Thread thread = new Thread(() -> System.out.println("Hello world")); // 创建一个线程 System.out.println(thread.getState()); // 此时线程的状态为NEW thread.start(); // 启动线程,状态为RUNNING System.out.println(thread.getState()); try { thread....
*/voidstart(){t=newThread(()->{while(!stop){//判断当前线程是否被打断System.out.println("正在监控系统...");try{Thread.sleep(3*1000L);//执行 3 秒System.out.println("任务执行 3 秒");System.out.println("监控的系统正常!");}catch(InterruptedException e){System.out.println("任务执行被中...
stop()方法 stop()方法会真的杀死线程。如果线程持有ReentrantLock锁,被stop()的线程并不会自动调用ReentrantLock的unlock()去释放锁,那其他线程就再也没机会获得ReentrantLock锁, 这样其他线程就再也不能执行ReentrantLock锁锁住的代码逻辑。所以该方法就不建议使用了, 类似的方法还有suspend()和resume()方法, 这两个方...
privatevolatilebooleanstop=false; /** * 启动一个线程监控系统 */ voidstart(){ t =newThread(() -> { while(!stop) {//判断当前线程是否被打断 System.out.println("正在监控系统..."); try{ Thread.sleep(3*1000L);//执行 3 秒 System.out.println("任务执行 3 秒"); System.out.println("...
sm.start(); try { //运行 10 秒后停止监控 Thread.sleep(10 * 1000); } catch (InterruptedExceptione) { e.printStackTrace(); } System.out.println("监控任务启动 10 秒后,停止..."); sm.stop(); } } /*系统监控器*/ class SystemMonitor { ...
newThread(mRunner).start(); for(inti =0; i <1000; i++) { System.out.println(" ---"+ Thread.currentThread()); } // Set message to stop the thread. mRunner.makeStop(); } } // The Runnable interface should be implemented by any class whose instances are intended to be executed...
StopThread thread = new StopThread(); thread.start(); } public static void main(String[] args) { testStopThread(); } } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22.
线程停止的机制比较特别。在Java层面,JDK会创建一个ThreadDeath对象,该类继承自Error,然后传给JVM_StopThread停止线程,如代码清单4-7所示:代码清单4-7 线程停止 JVM_ENTRY(void, JVM_StopThread(...))// 获取JDK传入的ThreadDeath对象,确保不为空oop java_throwable = JNIHandles::resolve(throwable);if(java...
我们经常需要在java中用到thread,我们知道thread有一个start()方法可以开启一个线程。那么怎么关闭这个线程呢? 有人会说可以用Thread.stop()方法。但是这个方法已经被废弃了。 根据Oracle的官方文档,Thread.stop是不安全的。因为调用stop方法的时候,将会释放它获取的所有监视器锁(通过传递ThreadDeath异常实现)。如果有资...
Thread thread = new MyThread(); thread.start(); try { Thread.sleep(2000); thread.interrupt(); System.out.println("stop 1??" + thread.interrupted()); System.out.println("stop 2??" + thread.interrupted()); } catch (InterruptedException e) { ...