zoukankan      html  css  js  c++  java
  • 线程的休眠和中断

    在程序中允许一个线程进行暂时的休眠,直接使用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();
        }
    }

  • 相关阅读:
    源码阅读笔记 BiLSTM+CRF做NER任务(一)
    leetcode题 寻找两个有序数组的中位数
    动手实现感知机算法,多分类问题
    剪绳子 牛客网-剑指Offer_编程题
    [SCOI2016]妖怪 牛客网的ACM省选题,个人看法,欢迎交流
    BERT 学习笔记
    解决图着色问题 python代码实现
    维吉尼亚密码及程序实现
    迪菲-赫尔曼密钥交换
    分布式系统组件之配置中心
  • 原文地址:https://www.cnblogs.com/vonk/p/3894083.html
Copyright © 2011-2022 走看看