(并发)线程的处理
来源:互联网 发布:属下知罪by枯目下 编辑:程序博客网 时间:2024/05/22 23:25
休眠
在之前已经使用了yield(),如果使用sleep()则之前的实例输出结果为,
public class LiftOff implements Runnable{ protected int countDown = 5; private static int taskCount = 0; private final int id = taskCount++; public LiftOff(){} public LiftOff(int countDown){ this.countDown = countDown; } public String status(){ return "#" + id + "(" + (countDown > 0 ? countDown : "liftoff!") + "),"; } public void run() { while(countDown-- > 0){ System.out.print(status()); try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(); }}public static void main(String[] args) { ExecutorService exec = Executors.newFixedThreadPool(1); for (int i = 0; i < 6; i++) { exec.execute(new LiftOff()); } exec.shutdown(); }//out#0(4),#0(3),#0(2),#0(1),#0(liftoff!),#1(4),#1(3),#1(2),#1(1),#1(liftoff!),#2(4),#2(3),#2(2),#2(1),#2(liftoff!),#3(4),#3(3),#3(2),#3(1),#3(liftoff!),#4(4),#4(3),#4(2),#4(1),#4(liftoff!),#5(4),#5(3),#5(2),#5(1),#5(liftoff!),
可以看出来输出是很有规律的,但是这也是保证在只有一个线程在执行,如果有多个,那么线程之间会依旧争抢时间片段。具体的执行顺序依赖与底层的线程机制,这个机制会根据操作系统的不同而产生不同的结果。sleep()会抛出异常InterruptedException,并且在run()被捕获,这是因为异常不能跨线程传播。
后台线程
在线程启动之前,调用setDaemon()方法,才能把它设置为后台线程。如果在所有非后台线程运行结束后,后台线程也会被杀死。以下代码可以修改最后main中的sleep()方法,来看其效果。该线程创建的是显示的线程。通过编写定制的ThreadFactory可以定制由Executor创建的线程的属性。
public class SimpleDaemons implements Runnable { public void run() { try { while (true) { TimeUnit.MILLISECONDS.sleep(100); System.out.println(Thread.currentThread() + " " + this); } } catch (InterruptedException e) { System.out.println("sleep() interrupted"); } } public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 10; i++) { Thread daemon = new Thread(new SimpleDaemons()); daemon.setDaemon(true); daemon.start(); } System.out.println("All daemons started"); TimeUnit.MILLISECONDS.sleep(175); }}
阅读全文
1 0
- (并发)线程的处理
- java服务对线程并发的处理
- sping是怎么处理线程并发的
- 线程锁 线程并发处理 | 异步调用委托的使用
- Spring如何处理线程并发
- Spring如何处理线程并发
- Spring如何处理线程并发
- Spring如何处理线程并发
- Spring如何处理线程并发
- Spring如何处理线程并发
- Spring如何处理线程并发
- Spring如何处理线程并发
- Spring如何处理线程并发
- Spring如何处理线程并发
- java线程 如何处理并发
- Spring如何处理线程并发
- Spring如何处理线程并发
- Spring如何处理线程并发
- JAVA中枚举类型enum综合详解
- 【SpringCloud】(十五):Zuul的基本应用,反向代理和负载均衡
- 网易2018校招编程题集合1
- mysql数据库中的表不存在,可以查看的问题
- AnyConnect卸载不完全,造成无法重新安装的解决办法 For Mac
- (并发)线程的处理
- linux中的数据库管理
- mysql数据类型
- python_静态属性,类方法,静态方法
- hdu 6112 基姆拉尔森计算公式
- C++中static_cast, dynamic_cast用法
- acm练习:喷水装置(一)
- Linux字符界面、VI编辑器
- MYSQL语句汇总 转载