漫谈并发编程(二):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 ...
随机推荐
- Java多线程实现生产者消费者延伸问题
在操作系统中有一类问题被称为生产者消费者问题:意为,有数个生产者生产产品,有数个消费者消费产品,他们共享一定数量的缓存. 这里用java多线程编程,实现生产者消费者问题的一种延伸,橘子苹果问题. 题目 ...
- 页面爬虫(获取其他页面HTML)加载到自己页面
//前台 <div id="showIframe"></div> $(document).ready(function() { var url = &quo ...
- OpenCV编程->Windows7下调用iPhnoe摄像头
////////////////////////////////////////////////////////////// 指尖热度原创,转载请注明来自http://blog.csdn.net/s ...
- JS - 循环添加 DropDownList(Select)
代码: <td style="padding-left: 10px;"> <select id="ddl_picture_3"> < ...
- Servlet的学习(三)
本篇接上一篇<Servlet的学习(二)> ,主要讲诉如何使用MyEclipse来开发Servlet,和导入Servlet所需要的源代码. 现在我们来创建一个web应用,就叫[myserv ...
- 设计模式之Prototype(c++)
Prototype模型: 作用: 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象----克隆(clone)对象. Prototype模型类图如下: 形象说明:如果客户想配钥匙(Conc ...
- Mac AppStore 登陆提示 未知错误
Mac Book 登陆的时候提示未知错误,刚开始以为是需要内建网卡后来才得知: 如果是黑苹果,或者是网卡没有对应上的,需要内建网卡 mac 系统默认的是无线网卡en0 其他都网卡 以此类推 如果是ma ...
- 单元测试工具 SmokeTest
.NET 程序集单元测试工具 SmokeTest Smoke Test(冒烟测试),也称Regression Test(回归测试),是对软件的安装和基本功能的测试.一般地我们使用脚本来实现Smoke ...
- Android SDK Manager安装报错
安装出错了,上网百度一大堆说法,又说版本兼容问题的,有说http换https的,我这个菜鸟真搞不明白,自己捣腾一下午总算弄上去了! 问题: 安装完Eclipse和ADT却无法更新SDK. 启动Andr ...
- flask开发restful api
flask开发restful api 如果有几个原因可以让你爱上flask这个极其灵活的库,我想蓝图绝对应该算上一个,部署蓝图以后,你会发现整个程序结构非常清晰,模块之间相互不影响.蓝图对restfu ...