goback add

java例程练习(多线程[sleep()方法])

4318 点击·0 回帖
灯火互联
楼主

import java.util.*;
public class Test {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
        try {
            Thread.sleep(10000);//主线程睡眠
            
        } catch(interruptedException e) { }
        
        thread.interrupt();          //-----------不是最好的方法
        //thread.flag = false;       //-----------此方法是终止线程的推荐方法                          
        
    }
}

class MyThread extends Thread {
    boolean flag = true;
    public void run() {
        //每隔一秒钟打印一次时间
        while(flag) {
            System.out.println
                ("====" + new Date() + "====");
            
            try{
                sleep(1000);
            } catch(InterruptedException e) { //----此异常必须处理
                return;
            }
        }
    }
}

喜欢0 评分0