Java Hour 27 Concurrent
有句名言,叫做10000小时成为某一个领域的专家。姑且不辩论这句话是否正确,让我们到达10000小时的时候再回头来看吧。
27 Hours.
本小时主要过一下多线程相关的基本API.
Defining tasks
package mike.qian.hello;
public class LiftOff implements Runnable {
protected int countDown = 10; // Default
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOff() {
}
public LiftOff(int countDown) {
this.countDown = countDown;
}
public String status() {
return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "), ";
}
public void run() {
while (countDown-- > 0) {
System.out.print(status());
Thread.yield();
}
}
}
一个线程主要是为了驱动一个task. 只要实现一个Runnable 接口就表示这是一个task.
Thread.yield 这个是可选了,表明允许CPU从当前线程中滚出去干其他事情去。
package mike.qian.hello;
public class Application {
public static void main(String[] args) {
Thread t = new Thread(new LiftOff());
t.start();
System.out.println("Waiting for LiftOff");
}
}
package mike.qian.hello;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Application {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++)
exec.execute(new LiftOff());
exec.shutdown();
System.out.println("Waiting for LiftOff");
}
}
带返回值的线程
package mike.qian.hello;
import java.util.concurrent.Callable;
class TaskWithResult implements Callable<String> {
private int id;
public TaskWithResult(int id) {
this.id = id;
}
public String call() {
return "result of TaskWithResult " + id;
}
}
package mike.qian.hello;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Application {
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 {
// get() blocks until completion:
System.out.println(fs.get());
} catch (InterruptedException e) {
System.out.println(e);
return;
} catch (ExecutionException e) {
System.out.println(e);
} finally {
exec.shutdown();
}
}
}
看到这个future, 瞬间石化了,好山寨的命名。
守护线程
守护线程就是后台线程,当所有前台线程退出后,程序将退出。
内部类的使用
package mike.qian.hello;
import java.util.concurrent.*;
import static java.lang.System.out;
// Using a named inner class:
class InnerThread1 {
private int countDown = 5;
private Inner inner;
private class Inner extends Thread {
Inner(String name) {
super(name);
start();
}
public void run() {
try {
while (true) {
out.println(this);
if (--countDown == 0)
return;
sleep(10);
}
} catch (InterruptedException e) {
out.println("interrupted");
}
}
public String toString() {
return getName() + ": " + countDown;
}
}
public InnerThread1(String name) {
inner = new Inner(name);
}
}
// Using an anonymous inner class:
class InnerThread2 {
private int countDown = 5;
private Thread t;
public InnerThread2(String name) {
t = new Thread(name) {
public void run() {
try {
while (true) {
out.println(this);
if (--countDown == 0)
return;
sleep(10);
}
} catch (InterruptedException e) {
}
}
public String toString() {
return getName() + ": " + countDown;
}
};
t.start();
}
}
// Using a named Runnable implementation:
class InnerRunnable1 {
private int countDown = 5;
private Inner inner;
private class Inner implements Runnable {
Thread t;
Inner(String name) {
t = new Thread(this, name);
t.start();
}
public void run() {
try {
while (true) {
out.println(this);
if (--countDown == 0)
return;
TimeUnit.MILLISECONDS.sleep(10);
}
} catch (InterruptedException e) {
out.println("sleep() interrupted");
}
}
public String toString() {
return t.getName() + ": " + countDown;
}
}
public InnerRunnable1(String name) {
inner = new Inner(name);
}
}
// Using an anonymous Runnable implementation:
class InnerRunnable2 {
private int countDown = 5;
private Thread t;
public InnerRunnable2(String name) {
t = new Thread(new Runnable() {
public void run() {
try {
while (true) {
out.println(this);
if (--countDown == 0)
return;
TimeUnit.MILLISECONDS.sleep(10);
}
} catch (InterruptedException e) {
out.println("sleep() interrupted");
}
}
public String toString() {
return Thread.currentThread().getName() + ": " + countDown;
}
}, name);
}
}
// A separate method to run some code as a task:
class ThreadMethod {
private int countDown = 5;
private Thread t;
private String name;
public ThreadMethod(String name) {
this.name = name;
}
public void runTask() {
if (t == null) {
t = new Thread(name) {
public void run() {
try {
while (true) {
out.println(this);
if (--countDown == 0)
return;
sleep(10);
}
} catch (InterruptedException e) {
out.println("sleep() interrupted");
}
}
public String toString() {
return getName() + ": " + countDown;
}
};
t.start();
}
}
}
public class Application {
public static void main(String[] args) {
new InnerThread1("InnerThread1");
new InnerThread2("InnerThread2");
new InnerRunnable1("InnerRunnable1");
new InnerRunnable2("InnerRunnable2");
new ThreadMethod("ThreadMethod").runTask();
}
} /* (Execute to see output) */// :~
这里包含了内部类,匿名内部类,相关的内容下个小时补上。
后面茫茫多的内容
其实这块东西和.NET 大同小异,但是东西是茫茫多的,暂且略过不表。
Java Hour 27 Concurrent的更多相关文章
- Java集合及concurrent并发包总结(转)
Java集合及concurrent并发包总结(转) 1.集合包 集合包最常用的有Collection和Map两个接口的实现类,Colleciton用于存放多个单对象,Map用于存放Key-Valu ...
- Java并发包concurrent——ConcurrentHashMap
转: Java并发包concurrent——ConcurrentHashMap 2018年07月19日 20:43:23 Bill_Xiang_ 阅读数 16390更多 所属专栏: Java Conc ...
- java多线程管理 concurrent包用法详解
我们都知道,在JDK1.5之前,Java中要进行业务并发时,通常需要有程序员独立完成代码实现,当然也有一些开源的框架提供了这些功能,但是这些依然没有JDK自带的功能使用起来方便.而当针对高质量 ...
- java 线程之concurrent中的常用工具 CyclicBarrier
一.CyclicBarrier CyclicBarrier是一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point).在涉及一组固定大小的线程的程序 ...
- java 多线程 27 :多线程组件之CountDownLatch
前言 在多线程环境下,JDK给开发者提供了许多的组件供用户使用(主要在java.util.concurrent下),使得用户不需要再去关心在具体场景下要如何写出同时兼顾线程安全性与高效率的代码.之前讲 ...
- 【java多线程】ConCurrent并发包 - Lock详解
synchronized的缺陷 我们知道,可以利用synchronized关键字来实现共享资源的互斥访问. Java 5在java.util.concurrent.locks包下提供了另一种来实现 ...
- Java集合及Concurrent并发包总结
1.集合包 集合包最常用的有Collection和Map两个接口的实现类,Colleciton用于存放多个单对象,Map用于存放Key-Value形式的键值对. Collection中最常用的又分为两 ...
- Java 第27章 JDBC
JDBC 模版 JDBC 的工作原理 JDBC API 提供者:Sun公司 内容:供程序员调用的接口与类,集成在java.sql 和javax.sql 包中,如: DriverManager 类 Co ...
- java基础27 单例集合Collection及其常用方法
1.集合 集合是存储对象数据的集合容器 1.1.集合比数组的优势 1.集合可以存储任意类型的数据,数组只能存储同一种数据类型的数据 2.集合的长度是变化的,数组的长度是固定的 1.2.数组:存储 ...
随机推荐
- UVa OJ 197 - Cube (立方体)
Time limit: 30.000 seconds限时30.000秒 Problem问题 There was once a 3 by 3 by 3 cube built of 27 smaller ...
- hdu 1008 Elevator
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Description The hig ...
- iptables一些经常忘掉易混淆的参数
-A:新增加一条规则,该规则在原规则的最后面 -p:规定应用于哪种数据包,例如:tcp,udp等 -d:(destination),表示目标IP或网络 -s:(source),表示源IP或网络 -j: ...
- latex+bibtex+jabref(zz)
很好的的latex使用心得: bibtex现学现卖 http://derecks.blog.sohu.com/118984444.html latex+bibtex+jabref http://blo ...
- Python2.x与Python3.x的区别
这个星期开始学习Python了,因为看的书都是基于Python2.x,而且我安装的是Python3.1,所以书上写的地方好多都不适用于Python3.1,特意在Google上search了一下3.x和 ...
- 只能输入汉字js脚本
<html> <head> <meta http-equiv="Content-Type" content="text/html" ...
- Ubuntu 12.04 安装 Chrome浏览器
1,先到chrome官网下载一个安装包 http://www.google.com/intl/zh-CN/chrome/ 2,ctrl+alt+t 打开终端. 3,在终端里输入sudo apt-get ...
- Servlet的生命周期及filter,servletRequest和servletResponse
序,Web应用中,Servlet和Filter是很重要的两个概念,一定要理解透彻. 一.Servlet类 继承自HttpServlet,HttpServlet是一个抽象类,主要包含的方法有init,s ...
- 证明ln2=0 和 2=1
我们知道下式成立: \begin{equation}\ln(1+x)=x-\frac{x^2}{2}+\frac{x^3}{3}-\frac{x^4}{4}+\ldots\label{eq1}\end ...
- zoj.3868.GCD Expectation(数学推导>>容斥原理)
GCD Expectation Time Limit: 4 Seconds Memory Limit: 262144 KB ...