漫谈并发编程(二):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 ...
随机推荐
- 基于visual Studio2013解决面试题之0504单链表逆序
题目
- 基于visual Studio2013解决C语言竞赛题之1054抽牌游戏
题目 解决代码及点评 /************************************************************************/ /* 54 ...
- HTML5 input placeholder 颜色 改动
David Murdoch:Chrome支持input=[type=text]占位文本属性,但下列CSS样式却不起作用: CSS input[placeholder], [placeholder], ...
- Metasploit学习之msf连接数据库
kali使用metasploit开启数据服务: 首先,初次使用系统要初始化建立数据库msf3, 否则的话 /opt/metasploit/apps/pro/ui/config/databse.yml不 ...
- clear、REFRESH、free区别
clear可以清楚一个工作区或变量.但是如果该内表是带表头的,清空内表时需要在该内表后加[].例如:clear gt_tab[]. free可以清空带表头的内表但是不会清空这个带表头内表的表头,但是也 ...
- 特么的. 最终把 amobbs 的站长阿莫(莫进明)给回骂了一顿.
起因: 假设你居住的地方,要上马PX等高污染的项目,你会怎么做. 鼓动别人上街暴力示威与军警对抗. 自己待在家里支持怂恿. 这样的人真心猥琐! 鉴于他常常私自改动帖子, 在此截图留存. 真特么没劲. ...
- C 编程最佳实践(书写风格)
简介本文是为了满足开发人员的需要而写的.我们总结了一套指南,无论作为开发人员还是顾问,这些指南多年来一直都很好地指导着我们,我们把它们作为建议提供给您,希望对您的工作有所帮助.您也许不赞同其中的某些指 ...
- 不是技术牛人,如何拿到国内IT巨头的Offer(转)
不久前,byvoid面阿里星计划的面试结果截图泄漏,引起无数IT屌丝的羡慕敬仰.看看这些牛人,NOI金牌,开源社区名人,三年级开始写Basic…在跪拜之余我们不禁要想,和这些牛人比,作为绝大部分技术屌 ...
- 普联的路由器TL-WR842N和TL-WR845N还有 TL-WR847N哪一个更好,我是家用
http://zhidao.baidu.com/question/525244706.html?fr=ala&device=mobile&ssid=0&from=844b&am ...
- JavaScript面向对象编程(10)高速构建继承关系之对象拷贝
前面的样例我们是通过构造器创建对象.而且希望该对象继承来自另外一个构造器的对象 我们也能够直接面向一个对象来达成继承的目的.使用下属步骤: 1.拷贝一个对象 2.给新对象加入属性 /** * 通过拷贝 ...