漫谈并发编程(二):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 ...
随机推荐
- 相遇Qt5
使用Qt5.x版本中的不同方面来开发应用程序,着重于新的Qt Quick的技术,提供了编写C++后端的必要内容,并扩展了Qt Quick. 本章提供了关于Qt5高层次的概述.它对开发者有效的展 ...
- GDI+: Curved Shapes
原文 http://www.functionx.com/vcsharp2003/gdi/curves.htm Curves Introduction to Curves A curve is ...
- hibernate解决oracle的id自增?
以前做SSH项目时,涉及到的数据库是mySQL,只需将bean的配置文件id设为native 就可以实现表id的自增. 现在用到了Oracle,当然知道这样是不行的啦,那么用序列自增? 我在网络上搜索 ...
- MSSQL- select @@identity的用法
转载自:http://blog.163.com/zhangqian_sms/blog/static/544483382008925112539620/ 用select @@identity得到上一次插 ...
- Vanya and Lanterns
Description Vanya walks late at night along a straight street of length l, lit by n lanterns. Consid ...
- Firemonkey绑定对象列表
在实现Firemonkey绑定对象列表的过程中,我遇到的一些现有教程当中没有提到的细节,分享一下. 1.追加对象 用Navigator插入记录,位置总是在当前记录之前插入,没有在最后追加一个对象的方法 ...
- 积累的VC编程小技巧之工具条和状态条
1.工具条和状态条中控件的添加: 方法⑴.只能在ToolBar里创建控件:首先,在ToolBar中创建一个Button,其ID为ID_TOOL_COMBO(我们要将创建的控件放在该Button的位置上 ...
- 动态修改PE文件图标(使用UpdateResource API函数)
PE文件的图标存储在资源文件中,而操作资源要用到的API函数就是UpdateResource首先我们需要先了解一下ICO格式,参考资料:http://www.moon-soft.com/program ...
- Marshal UTF8 Strings in .NET
原文:Marshal UTF8 Strings in .NET Marshal UTF8 Strings in .NET Wow, what a pain in the butt. .NET stri ...
- 解决Myeclipse在port占用,导致tomcat无法启动。(Linux)
本文来源于:http://blog.csdn.net/svitter 引文:http://www.2cto.com/os/201305/209285.html { ubuntu查看占用某port的程序 ...