public static void sleep(Long millis):使当前正在执行的线程以指定的毫秒数暂停(暂时停止执行)。毫秒数结束之后,线程继卖执行

sleep(简称线程休眠)

举例:

 

 

 举例:

public static void main(String[] args) throws IOException {
        do {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            Date date = new Date();
            System.out.println(simpleDateFormat.format(date));
            Thread.sleep(1000);
        }while(true);
    }

举例:

public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + "线程开始执行");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(threadName + "任务执行完毕");
        }, "work");
        thread.start();
        System.out.println("main线程执行");
    }

举例:

    public static void main(String[] args) {
        Thread t1 = new Thread(new myThread(), "thread1");
        Thread t2 = new Thread(new myThread(), "thread2");
        t1.start();
        t2.start();
    }
}

class myThread implements Runnable{
    public void run() {
        System.out.println(Thread.currentThread().getName()+"开始执行");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"执行结束");
    }
}

 

 

 

创建多线程程序的第二种方式_实现Runnable接口

创建多线程的第二种方法:实现Runnable接口

Runnable接口一个由哪写打算通过某一线程执行其实例的类来实现。类必须定义一个称为run的无参数方法

java.lang.Thread类的构造方法

Thread(Runnable target)分配新的Thread对象

Thread(Runnable target,String name)分配新的Thread对象

实现步骤:

1.创建一个Runnable接口的实现类

2.在实现类中重写Runnable接口的run方法,设置线程任务

3.创建一个Runnable接口的实现类对象

4.创建Thread类对象,构造方法中传递Runnable接口的实现类对象

5.调用Thread类中的start方法,开启新的线程执行run方法

 

举例:

 

 

 

 举例:Thread

 

 

举例:Runnable

 

 

 

posted on 2022-07-08 15:05  淤泥不染  阅读(41)  评论(0编辑  收藏  举报