posts - 397,comments - 0,views - 25332

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   淤泥不染  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示