漫谈并发编程(二):java线程的创建与基本控制
java线程的创建
public class LiftOff implements Runnable {
protected int countDown = 10;
private static int taskCount = 0;
private final int id = taskCount++;
public void run() {
while(countDown-- > 0 ) {
System.out.print("#"+id+"("+countDown+"). ");
Thread.yield();
}
}
}
public class MainThread {
public static void main(String[] args) {
LiftOff lauch = new LiftOff();
lauch.run();
}
}
.png)
public class BasicThreads {
public static void main(String[] args) {
Thread t = new Thread(new LiftOff());
t.start();
System.out.println("Waiting for LiftOff");
}
}
.png)
public class MoreBasicThreads {
public static void main(String args[]) {
LiftOff liftOff = new LiftOff();
for(int i = 0; i < 5; i++) {
new Thread(liftOff).start();
}
}
}
.png)
Executor
public class CachedThreadPool {
public static void main(String []args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0 ; i < 5; i++)
exec.execute( new LiftOff() );
exec.shutdown();
}
}
public class FixedThreadPool{
public static void main(String []args) {
ExecutorService exec = Executors.FixedThreadPool();
for(int i = 0 ; i < 5; i++)
exec.execute( new LiftOff() );
exec.shutdown();
}
}
public class SingleThreadExecutor {
public static void main(String []args) {
ExecutorService exec = Executors.newSingleThreadExecutor();
for(int i = 0 ; i < 5; i++)
exec.execute( new LiftOff() );
exec.shutdown();
}
}
从任务中产生返回值
class TaskWithResult implements Callable<String> {
private int id;
public TaskWithResult(int id) {
this.id = id;
} @Override
public String call() throws Exception {
return "result of TaskWithResult " + id;
}
} public class CallableDemo {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for(int i = 0; i < 10;i++) {
results.add( exec.submit(new TaskWithResult(i)));
}
for(Future<String> fs : results)
try {
System.out.println(fs.get());
} catch (InterruptedException e) {
System.out.println(e);
} catch (ExecutionException e) {
System.out.println(e);
}
exec.shutdown();
}
}
休眠
优先级
public class SimplePriorities implements Runnable{
private int countDown = 5;
private double d;
private int priority;
public SimplePriorities(int priority) {
this.priority = priority;
}
public String toString( ) {
return Thread.currentThread() + " : " + countDown;
}
public void run( ) {
Thread.currentThread().setPriority( priority );
while(true) {
for(int i = 1 ; i < 100000 ; i++) {
d += (Math.PI + Math.E) / (double)i;
if(i % 1000 == 0)
Thread.yield();
}
System.out.println(this);
if( --countDown == 0) return;
}
}
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 5; i++)
exec.execute( new SimplePriorities(Thread.MIN_PRIORITY));
exec.execute( new SimplePriorities(Thread.MAX_PRIORITY));
exec.shutdown();
}
}
让步
后台线程
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 Exception {
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 );
}
}
public class DaemonThreadFactory implements ThreadFactory{
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
} public class DaemonFromFactory implements Runnable {
@Override
public void run() {
try{
while(true) {
TimeUnit.MILLISECONDS.sleep(100);
System.out.println( Thread.currentThread() + " " +this);
}
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
public static void main(String args[]) throws Exception {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 10; i++)
exec.execute(new DaemonFromFactory());
System.out.println("All daemons started");
TimeUnit.MILLISECONDS.sleep(500);
}
}
增加一个线程
捕获异常
class ExceptionThread2 implements Runnable {
public void run() {
Thread t = Thread.currentThread();
System.out.println("run() by " + t);
System.out.println("eh = " + t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
} class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e);
}
} class HandlerThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
System.out.println(this + " creating new Thread");
Thread t = new Thread(r);
System.out.println("created " + t);
t.setUncaughtExceptionHandler( new MyUncaughtExceptionHandler());
System.out.println("eh = " + t.getUncaughtExceptionHandler());
return t;
}
} public class CaptureUncaughtException {
public static void main(String []args) {
ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
}
public class SettingDefaultHandler {
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(
new MyUncaughtExceptionHandler( ) );
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new ExceptionThread());
}
}
漫谈并发编程(二):java线程的创建与基本控制的更多相关文章
- Java并发编程(01):线程的创建方式,状态周期管理
本文源码:GitHub·点这里 || GitEE·点这里 一.并发编程简介 1.基础概念 程序 与计算机系统操作有关的计算机程序.规程.规则,以及可能有的文件.文档及数据. 进程 进程是计算机中的程序 ...
- Java并发编程:Java线程池
转载自:http://www.cnblogs.com/dolphin0520/p/3932921.html 在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题 ...
- Java并发编程:Java线程池核心ThreadPoolExecutor的使用和原理分析
目录 引出线程池 Executor框架 ThreadPoolExecutor详解 构造函数 重要的变量 线程池执行流程 任务队列workQueue 任务拒绝策略 线程池的关闭 ThreadPoolEx ...
- Java并发编程:Java的四种线程池的使用,以及自定义线程工厂
目录 引言 四种线程池 newCachedThreadPool:可缓存的线程池 newFixedThreadPool:定长线程池 newSingleThreadExecutor:单线程线程池 newS ...
- Java并发编程二三事
Java并发编程二三事 转自我的Github 近日重新翻了一下<Java Concurrency in Practice>故以此文记之. 我觉得Java的并发可以从下面三个点去理解: * ...
- 并发编程——认识java里的线程
本文系作者 chaoCode原创,转载请私信并在文章开头附带作者和原文地址链接. 违者,作者保留追究权利. 前言 并发编程在我们日常开发中是时时刻刻都有在用的,只不过大部分的代码底层已经帮我们去做了一 ...
- Java并发编程系列-(2) 线程的并发工具类
2.线程的并发工具类 2.1 Fork-Join JDK 7中引入了fork-join框架,专门来解决计算密集型的任务.可以将一个大任务,拆分成若干个小任务,如下图所示: Fork-Join框架利用了 ...
- Java线程:创建与启动
Java线程:创建与启动 一.定义线程 1.扩展java.lang.Thread类. 此类中有个run()方法,应该注意其用法: public void run() 如果该线程是使用独立的 R ...
- 【并发编程】Java并发编程传送门
本博客系列是学习并发编程过程中的记录总结.由于文章比较多,写的时间也比较散,所以我整理了个目录贴(传送门),方便查阅. [并发编程系列博客传送门](https://www.cnblogs.com/54 ...
随机推荐
- Object-c @property的用法
property是一种代码生成机制,可以生成不同类型的getter/setter函数,特别是假设你想要用点(.)操作符号来存取变量的话,你就能必须使用property. 怎样使用? 使用方法如:@pr ...
- webdynpro的select_option示例
需求,输入航线代码和航线编号区间,查询记录存在表中显示,并不是alv显示 1.使用组件WDR_SELECT_OPTIONS. 2.在组件控制器中加入以下组件 3.在视图属性中也添加该组件 4.创建节点 ...
- Appium Server 传递的基本参数
Appium Server 传递的基本参数 官方列表 Appium server capabilities Capability Description Values automationName ...
- JavaScript快速入门(五)——表达式运算
赋值运算 赋值运算的形式为左值 = 右值.如果同个表达式中有多个赋值运算,则从右到左运算.例如: a = b = c; // 和下面两行等价 b = c; a = b; 另外一种赋值运算的形式叫做复合 ...
- SilkTest Q&A 8
Q72.如何在一个testplan中运行所有的testcase? A72. 1.打开testplan 2.点击Run/Run All Tests菜单,SilkTest开始执行testplan中所有的t ...
- OSGi:生命周期层
前言 生命周期层在OSGi框架中属于模块层上面的一层,它的运作是建立在模块层的功能之上的.生命周期层一个主要的功能就是让你能够从外部管理应用或者建立能够自我管理的应用(或者两者的结合),并且给了应用本 ...
- Xamainr 地图之webview初探
一 说几点 当下移动开发主要实现方式有传统的Native以及新的混合开发想Rect.js,nodejs这些前段框架,其本质要么是原生控件来实现UI,要么html来实现UI.Xamarin其实也只是取巧 ...
- windows时间函数
介绍 我们在衡量一个函数运行时间,或者判断一个算法的时间效率,或者在程序中我们需要一个定时器,定时执 行一个特定的操作,比如在多媒体中,比如在游戏中等,都会用到时间函数.还比如我们通过记 ...
- Delphi经典网站收藏
http://delphi.icm.edu.pl/ 波兰的Delphi控件网站 http://dev.rdxx.com/Delphi/ 国内的编程网站 非常全面 http://oracle.ch ...
- JAVA网络爬虫WebCollector深度解析——爬虫内核
WebCollector爬虫官网:https://github.com/CrawlScript/WebCollector 技术讨论群:250108697 怎样将爬虫内核导入自己的项目? 1.进入爬虫官 ...