首页 分享 Thread的基本用法——多线程

Thread的基本用法——多线程

来源:花匠小妙招 时间:2024-12-07 10:17

最新推荐文章于 2023-07-19 22:46:12 发布

进击小张 于 2022-04-24 21:12:46 发布

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

线程创建

public class test extends Thread{

@Override

public void run() {

System.out.println("我是一个线程");

}

public static void main(String[] args) {

test test1 = new test();

test1.start();

}

}

2.线程中断(使用interrupt)

private static void test2() {

Thread thread = new Thread(() -> {

while (true) {

Thread.yield();

if (Thread.currentThread().isInterrupted()) {

System.out.println("线程被中断,程序退出。");

return;

}

}

});

thread.start();

thread.interrupt();

}

3.线程等待(sleep())

public class ThreadDemo {

public static void main(String[] args) throws InterruptedException {

Runnable target = () -> {

for (int i = 0; i < 10; i++) {

try {

System.out.println(Thread.currentThread().getName()

+ ": 我还在工作!");

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println(Thread.currentThread().getName() + ": 我结束了!");

};

Thread thread1 = new Thread(target, "李四");

Thread thread2 = new Thread(target, "王五");

System.out.println("先让李四开始工作");

thread1.start();

thread1.join();

System.out.println("李四工作结束了,让王五开始工作");

thread2.start();

thread2.join();

System.out.println("王五工作结束了");

}

}

4.线程休眠(sleep)

public class ThreadDemo {

public static void main(String[] args) throws InterruptedException {

System.out.println(System.currentTimeMillis());

Thread.sleep(3 * 1000);

System.out.println(System.currentTimeMillis());

}

}

5.获取线程实例

public class test {

public static void main(String[] args) {

System.out.println( Thread.currentThread().getName());

}

}

相关知识

多线程并行与退出
Linux 下C语言多线程编程
玫瑰精油的基本用法
Python实例(六)
flower的词汇用法
精油护肤的正确用法 精油护肤的正确用法是什么
蜘蛛草的用法
Java十大经典案例源码解析与实战应用
茉莉花精油的用法
冒号的用法

网址: Thread的基本用法——多线程 https://www.huajiangbk.com/newsview939964.html

所属分类:花卉
上一篇: 真品玫瑰花 伪品钝叶蔷薇花
下一篇: 玫瑰月季蔷薇的区别

推荐分享