漫谈并发编程(二):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 ...
随机推荐
- 时间戳timestamp
1 时间戳 数据库中自动生成的 唯一的 二进制的数据,通常用作给数据表的行添加版本戳的机制. timestamp与时间和日期无关. timestamp存储大小为8字节. 一个数据表只能有一个times ...
- 如何将自定义标签封装成一个Jar包
当我们在一个web应用中开发好一些自定义标签的时候,这些自定义标签通常有标签处理器Java类,和一个描述这些标签tld文件,如果我们想在以后别的web工程中还能用上这些标签,可以将这些自定义标签封装在 ...
- TCP与UDP各自特点对比
UDP和TCP是我们最常用的两种通信方式,下面就两者之间的特点做一个对比: 1.UDP主要用在实时性要求高以及对质量相对较弱的地方,如流媒体. 2.TCP既然是面向连接的,那么运行环境必然要求其保证可 ...
- Mongdb 访问
http://114.55.75.xx/pics/201607040751367d21a38035bd4da7abd4473783f85f7a
- 关键部分CCriticalSection使用
类CCriticalSection的对象表示一个“临界区”,它是一个用于同步的对象,同一时刻仅仅同意一个线程存取资源或代码区.临界区在控制一次仅仅有一个线程改动数据或其他的控制资源时很实用.比如,在链 ...
- Delphi中获取某类的祖先类及其所在单元名称(使用GetTypeData(PClass.ClassInfo)函数,并且该类是从TPersistent类的派生类才可以这么使用)
前几天在CSDN社区看到一篇<如何得到自身单元名称>的帖子,其中一位名为sdzeng网友给出了答案.受此启发,自己写了一个函数,用来获取指定类的所有祖先类的名称及其所在的单元名称. //参 ...
- android使用篇(四) 注解依赖注入IOC实现绑定控件
在android使用篇(三) MVC模式中提到一个问题: 1) 视图层(View):一般採用XML文件进行界面的描写叙述,使用的时候能够很方便的引入,可是用xml编写了,又须要在Acitvity声明而 ...
- 窗体透明,但窗体上的控件不透明(简单好用)good
1.在Delphi中,设置窗体的AlphaBlend := true;AlphaBlendValue := 0-255; AlphaBlendValue越小窗体的透明度就越高.这种方法将会使窗体和窗体 ...
- Eclipse插件引入jar包的方法(转)
搞了两天,终于找到解决办法了.原来 Eclipse 插件项目引入外面的jar包不能用 build path---->add external jars的方法. 先说明两个概念:类加载器,O ...
- 【LeetCode】Min Stack 解题报告
[题目] Design a stack that supports push, pop, top, and retrieving the minimum element in constant tim ...