Java并发编程入门 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

sleep()

sleep是一个静态的本地方法,主要作用是使这个线程休眠一定时间,sleep的方法声明是这样的:

public static native void sleep(long millis) throws InterruptedException;

在使用的时候我们可以采取这样的方式。

         try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

方法中的参数1000代表的是休眠1秒,这个方法可以让我们很明显的观察多线程的变化。比如之前的代码可以改成:

public class Main {
    public static void main(String[] args){
        Thread thread1=new Thread(new TheThread());
        Thread thread2=new Thread(new TheThread());
        Thread thread3=new Thread(new TheThread());
        thread1.start();
        thread2.start();
        thread3.start();
        System.out.println("Main");
    }
}
class TheThread implements Runnable{
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getId() + ":" + i);
        }
    }
}
运行以上程序,查看结果