Java 读书笔记 21.1并发
来源:互联网 发布:融资租赁软件市场 编辑:程序博客网 时间:2024/06/03 07:20
并发
终于来到这里了,好开心;
线程定义
public class Liftoff implements Runnable{ //接口 @Override public void run() { //实现run方法 }}public static void main(String []arg){ //第一种 Liftoff liftoff = new Liftoff(); liftoff.run(); //第二种 Thread thread = new Thread(new Liftoff()); thread.start(); } }
Executor
public class MainThread { public static void main(String []arg) { //ExecutorService executorService = Executors.newCachedThreadPool(); // 每一个任务都创建新的线程 ExecutorService executorService = Executors.newFixedThreadPool(2); //同时只允许两个线程工作; for (int i1 = 0; i1 < i; i1++) { //new Thread(new Liftoff()).start(); executorService.execute(new Liftoff()); } executorService.shutdown(); System.out.println("wait"); }}
Callable
public class TaskWithResult implements Callable<String> { public static void main(String []arg) { ExecutorService executorService = Executors.newCachedThreadPool(); ArrayList<Future<String>> futures = new ArrayList<>(); for (int i = 0;i<10;i++) { futures.add(executorService.submit(new TaskWithResult(i))); } for (Future<String> fs : futures) { try { System.out.println(fs.get()); }catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { executorService.shutdown(); } } } private int id; public TaskWithResult(int id) { this.id= id; } @Override public String call() throws Exception { //实现call方法,用以返回值; return "result "+id; }}
优先级
public class Priority implements Runnable{ public static void main(String []arg) { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i=0;i<5;i++) { executorService.execute(new Priority(Thread.MIN_PRIORITY)); } executorService.execute(new Priority(Thread.MAX_PRIORITY)); executorService.shutdown(); } private volatile double d; private int priority; private int countdown; public Priority(int priority) { this.priority = priority; } public String toString() { return Thread.currentThread() + " :"+countdown; } @Override 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 class SimpleDaemons implements Runnable { @Override public void run() { try { while (true) { TimeUnit.MILLISECONDS.sleep(500); System.out.println(Thread.currentThread()+""+this); } } catch (InterruptedException e) { e.printStackTrace(); System.out.println("interrupt"); } finally { System.out.println("finally"); //Main函数退出,后台直接跳出,finally不执行嘞 } } public static void main(String []arg) throws InterruptedException { for (int i=0;i<10;i++) { Thread deamon = new Thread(new SimpleDaemons()); deamon.setDaemon(true); deamon.start(); } System.out.println("all daemon started"); TimeUnit.SECONDS.sleep(5); //如果主线程不睡,就直接停止了,后台自动停止了 }}
后台线程所派生的子线程都是隐式的后台线程;
另外的线程定义方式
public class SimpleThread extends Thread { public SimpleThread() { start(); } @Override public void run() { super.run(); } public static void main(String []arg) { new SimpleThread(); }}
ps:
public class SimpleThread extends Thread { public SimpleThread() { start(); Thread.currentThread().setName("la"); //此时修改的其实是Main这个线程的名字 } @Override public void run() { Thread.currentThread().setName("la"); //run之后,修改的就是自己的啦; System.out.println(Thread.currentThread().getName()); super.run(); } public static void main(String []arg) { SimpleThread a= new SimpleThread(); a.setName("hello"); System.out.println(Thread.currentThread().getName()); }}
join
public class Sleep extends Thread { private int sleep; public Sleep(String name , int a) { super(name); sleep=a; start(); } public void run() { try { sleep(sleep); } catch (InterruptedException e) { System.out.println(getName()+"was interrupt"+isInterrupted()); return; } System.out.println(getName() + "has weaken"); }}
public class Join extends Thread { private Sleep sleep; public Join(String name ,Sleep sleep) { super(name); this.sleep=sleep; start(); } public void run() { try { sleep.join(); } catch (InterruptedException e) { System.out.println("interrupt"); } System.out.println(getName() + " complete"); } public static void main(String []arg) { Sleep sleep = new Sleep("sleep",1000); Sleep grumy = new Sleep("g",1500); Join d = new Join("do",sleep); Join p = new Join("po",grumy); grumy.interrupt(); }}output:gwas interruptfalsepo completesleephas weakendo complete
异常捕捉
主线程无法捕捉线程的异常,只能通过一个中介,在Thread附着一个异常处理器;
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ThreadFactory;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 { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("caught " + e); }}class HandlerThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { System.out.println(this + " creating new Thread"); Thread t = new Thread(r); System.out.println("created " + t + " ID:" + t.getId()); 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()); }}
0 0
- Java 读书笔记 21.1并发
- 《Java 并发实践》读书笔记
- java 并发编程读书笔记
- java并发-读书笔记
- 【Java并发编程】读书笔记
- Java 读书笔记 21.2 并发
- Java 读书笔记 21.4 并发
- java并发实战读书笔记
- <读书笔记--并发>二、java并发机制
- JAVA并发编程实践--读书笔记
- 《Java并发编程实战》读书笔记
- Java并发编程实践 读书笔记
- Java并发编程实践读书笔记
- 《Java并发编程实战》读书笔记
- java并发编程实战-读书笔记
- Effective Java读书笔记(四):并发
- 《Java并发编程实战》读书笔记
- 《java并发编程实战》读书笔记
- PHP-memcahce概念
- 272. Closest Binary Search Tree Value II
- python实现简单的图片隐写术
- redis数据对象底层结构图
- Git——Day2(git初始化及仓库创建)
- Java 读书笔记 21.1并发
- 浏览器的渲染原理
- Freecodecamp学习笔记(2)
- 跟踪分析Linux内核的启动过程
- 端口扫描—TCP Connect()
- HDU 4858 项目管理 (简单图+暴力)
- .NET Core 1.1日期解析无APi、SQL Server数据转换JSON
- 操作系统面试题目解析①
- HDU3347Calculate the expression 【map】