• 线程的休眠和中断


    在程序中允许一个线程进行暂时的休眠,直接使用Thread.sleep()方法即可实现休眠:

    class myThread11 implements Runnable {
        public void run() {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(5000);
                    System.out.println(Thread.currentThread().getName()
                            + " running " + i);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    }

    public class ThreadSleepDemo {
        public static void main(String[] args) {
            myThread11 m = new myThread11();
            new Thread(m, "von's thread").start();
        }
    }

    当一个线程运行时,另外一个线程可以直接通过interrupt()方法中断其运行状态:

    class myThread12 implements Runnable {
        public void run() {
            System.out.println("1,Begin run() method:");
            try {
                Thread.sleep(10000);
                System.out.println("2,Sleep have overd.");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                System.out.println("3,Sleep be stoped.");
                return;
            }
            System.out.println("4,Stop run() method normally.");
        }
    }

    public class ThreadInteruptDemo {
        public static void main(String[] args) {
            myThread12 vMyThread = new myThread12();
            Thread thread = new Thread(vMyThread, "vThread");
            thread.start();
            try {
                thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            thread.interrupt();
        }
    }

  • 相关阅读:
    别逃避,是时候来给JVM一记重锤了
    从CAS讲起,真正高性能解决并发编程的原子操作
    深入理解typedef
    【Valse首发】CNN的近期进展与实用技巧(上)
    基于深度学习的目标检测研究进展
    全卷积网络:从图像级理解到像素级理解
    产生式与判别式模型
    游戏后台杂谈:后台的语言、系统与构架
    优化人脸检测网络
    最长的回文子序列
  • 原文地址:https://www.cnblogs.com/vonk/p/3894083.html
Copyright © 2020-2023  润新知