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.数组:存储 ...
随机推荐
- 离线渲染中的不规则光源(Meshlight)
之前一直在考虑这样一个问题,在实际生活中的光源都是有体积的,但是图形学中,很多时候我们用简单的点光源,面光源,或者方向光来模拟实际生活中这些光源,势必会产生一些误差,同时导致很多效果不好做.那么在离线 ...
- codejumper的跳转代码
public void JumpToSource(vsCMPart location = vsCMPart.vsCMPartNavigate) { TextPoint startPoint = Ori ...
- web.config 加密/解密
(Aspnet_regiis.exe) 这样的一个工具,可以对站点的.config文件的节进行加密 方法: #> 加密:aspnet_regiis -pef "加密的web.confi ...
- msmms (一) sms与mms区别
sms与mms区别 SMS,Short Messaging Service短信业务,可以通过手机等移动设备发送文本型短信.SMS这个术语最早在80年代初期出现,但一直到了90年代初才开始进入商用市场, ...
- JavaScript 参数传递与变量复制
ECMAScript 变量可能包含两种不同数据类型的值:基本类型值和引用类型值. 基本类型值指的是简单的数据段,而引用类型值指那些可能由多个值构成的对象. 5 种基本数 ...
- (三)Linux命令基本格式以及文件处理命令
命令基本格式 (1)命令提示符 如下是命令行的命令提示符,以此为例,讲解含义. 其中: root 当前登录用户名 localhost 主机名 ~ 当前所在的目录(即家目录,用户登录的初始位置) # 超 ...
- linux cp命令参数及用法详解
cp (复制档案或目录)[root@linux ~]# cp [-adfilprsu] 来源档(source) 目的檔(destination)[root@linux ~]# cp [options] ...
- 使用Angular和Nodejs搭建聊天室
一,利用Node搭建静态服务器 这个是这个项目的底层支撑部分.用来支持静态资源文件像html, css, gif, jpg, png, javascript, json, plain text等等静态 ...
- ASP.NET使用FileUpload上传文件
前台代码: <asp:FileUpload ID="fuKeleyi" runat="server" /> <asp:Button ID=&q ...
- javascript 对象(DOM)document window history
Javascript对象 目录: window对象 document对象 history对象 navigator对象 window对象 所有浏览器都支持window对象,它表示浏览器窗口. 所有jav ...