------------- android培训、java培训、java学习型技术博客、期待与您交流! ------------
看java.util.concurrent 包及子包的 API 帮助文档 , 了解 java.util.concurrent.atomic 包, 查看 atomic 包文档页下面的介绍, 通过如下两个方法快速理解 atomic 包的意义:
线程池
线程池的概念与Executors类的应用
看java.util.concurrent 包及子包的 API 帮助文档 , 了解 java.util.concurrent.atomic 包, 查看 atomic 包文档页下面的介绍, 通过如下两个方法快速理解 atomic 包的意义:
AtomicInteger
类的
boolean compareAndSet(expectedValue, updateValue);
AtomicIntegerArray
类的
int
addAndGet
(int i, int delta);
顺带解释
volatile
类型的作用,需要查看
java
语言规范。
l
了解
java.util.concurrent.lock
包
线程池
线程池的概念与Executors类的应用
创建固定大小的线程池;
创建缓存线程池;
创建单一线程池
l
关闭线程池
shutdown
与
shutdownNow
的比较
l
用线程池启动定时器
调用ScheduledExecutorService的schedule方法,返回的ScheduleFuture对象可以取消任务。
支持间隔重复任务的定时方式,不直接支持绝对定时方式,需要转换成相对时间方式。
调用ScheduledExecutorService的schedule方法,返回的ScheduleFuture对象可以取消任务。
支持间隔重复任务的定时方式,不直接支持绝对定时方式,需要转换成相对时间方式。
package
cn.
itcast.
heima2;
import
java.
util.
concurrent.
ExecutorService;
import
java.
util.
concurrent.
Executors;
import
java.
util.
concurrent.
TimeUnit;
public
class
ThreadPoolTest {
/**
*
@param
args
*/
public
static
void
main(
String[]
args) {
//ExecutorService threadPool = Executors.newFixedThreadPool(3); //在线程池里增加固定3个线程
//ExecutorService threadPool = Executors.newCachedThreadPool(); //与任务匹配,自动增加线程数量
ExecutorService
threadPool
=
Executors.
newSingleThreadExecutor();
//单一线程,在线程池里使用一条线程
//并且当这条线程死掉后,线程池会重新生成一条新的线程来代替死去的线程
for(
int
i
=
1;
i
<=
10;
i
++){
final
int
task
=
i;
threadPool.
execute(
new
Runnable(){
@
Override
public
void
run() {
for(
int
j
=
1;
j
<=
10;
j
++){
try {
Thread.
sleep(
20);
}
catch (
InterruptedException
e) {
e.
printStackTrace();
}
System.
out.
println(
Thread.
currentThread().
getName()
+
" is looping of "
+
j
+
" for task of "
+
task);
}
}
});
}
System.
out.
println(
"all of 10 tasks have committed! ");
//threadPool.shutdownNow(); //任务结束后自动释放线程
//threadPool.shutdownNow();//释放当前线程,比如现在运行的有3条线程,执行10个任务,
//那么有3个任务会被先执行,然后就被释放掉了.剩下7个任务没有被运行
Executors.
newScheduledThreadPool(
3).
scheduleAtFixedRate(
new
Runnable(){
@
Override
public
void
run() {
System.
out.
println(
"bombing!");
}},
6,
2,
TimeUnit.
SECONDS);
}
}
callable 与 Future
读写锁
Condition //类似于传统线程里的wait 与 notify,基于Lock下使用,通常用来做同步互斥
public
class
CallableAndFuture {
/**
*
@param
args
*/
public
static
void
main(
String[]
args) {
ExecutorService
threadPool
=
Executors.
newSingleThreadExecutor();
Future
<
String
>
future
=
threadPool.
submit(
new
Callable
<
String
>()
{
public
String
call()
throws
Exception {
Thread.
sleep(
2000);
return
"hello";
};
}
);
System.
out.
println(
"等待结果");
try {
System.
out.
println(
"拿到结果:"
+
future.
get());
}
catch (
InterruptedException
e) {
e.
printStackTrace();
}
catch (
Exception
e) {
e.
printStackTrace();
}
ExecutorService
threadPool2
=
Executors.
newFixedThreadPool(
10);
CompletionService
<
Integer
>
completionService
=
new
ExecutorCompletionService
<
Integer
>(
threadPool2);
//提交一组任务交由Callable运行,只要有一个任务完成
//就返回一条
for(
int
i
=
1;
i
<=
10;
i
++){
final
int
seq
=
i;
completionService.
submit(
new
Callable
<
Integer
>() {
@
Override
public
Integer
call()
throws
Exception {
Thread.
sleep(
new
Random().
nextInt(
5000));
return
seq;
}
});
}
for(
int
i
=
0;
i
<
10;
i
++){
try {
System.
out.
println(
completionService.
take().
get());
}
catch (
InterruptedException
e) {
e.
printStackTrace();
}
catch (
ExecutionException
e) {
e.
printStackTrace();
}
}
}
}
读写锁
public
class
ReadWriteLockTest {
public
static
void
main(
String[]
args) {
final
Queue3
q3
=
new
Queue3();
for(
int
i
=
0;
i
<
3;
i
++)
{
new
Thread(){
public
void
run(){
while(
true){
q3.
get();
}
}
}.
start();
new
Thread(){
public
void
run(){
while(
true){
q3.
put(
new
Random().
nextInt(
10000));
}
}
}.
start();
}
}
}
class
Queue3{
private
Object
data
=
null;
//共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
ReadWriteLock
rwl
=
new
ReentrantReadWriteLock();
public
void
get(){
rwl.
readLock().
lock();
try {
System.
out.
println(
Thread.
currentThread().
getName()
+
" be ready to read data!");
Thread.
sleep((
long)(
Math.
random()
*
1000));
System.
out.
println(
Thread.
currentThread().
getName()
+
"have read data :"
+
data);
}
catch (
InterruptedException
e) {
e.
printStackTrace();
}
finally{
rwl.
readLock().
unlock();
}
}
public
void
put(
Object
data){
rwl.
writeLock().
lock();
try {
System.
out.
println(
Thread.
currentThread().
getName()
+
" be ready to write data!");
Thread.
sleep((
long)(
Math.
random()
*
1000));
this.
data
=
data;
System.
out.
println(
Thread.
currentThread().
getName()
+
" have write data: "
+
data);
}
catch (
InterruptedException
e) {
e.
printStackTrace();
}
finally{
rwl.
writeLock().
unlock();
}
}
}
public
class
ConditionCommunication {
public
static
void
main(
String[]
args) {
final
Business
business
=
new
Business();
new
Thread(
new
Runnable() {
@
Override
public
void
run() {
for(
int
i
=
1;
i
<=
50;
i
++){
business.
sub(
i);
}
}
}
).
start();
for(
int
i
=
1;
i
<=
50;
i
++){
business.
main(
i);
}
}
static
class
Business {
Lock
lock
=
new
ReentrantLock();
Condition
condition
=
lock.
newCondition();
private
boolean
bShouldSub
=
true;
public
void
sub(
int
i){
lock.
lock();
try{
while(
!
bShouldSub){
try {
condition.
await();
}
catch (
Exception
e) {
e.
printStackTrace();
}
}
for(
int
j
=
1;
j
<=
10;
j
++){
System.
out.
println(
"sub thread sequence of "
+
j
+
",loop of "
+
i);
}
bShouldSub
=
false;
condition.
signal();
}
finally{
lock.
unlock();
}
}
public
void
main(
int
i){
lock.
lock();
try{
while(
bShouldSub){
try {
condition.
await();
}
catch (
Exception
e) {
e.
printStackTrace();
}
}
for(
int
j
=
1;
j
<=
100;
j
++){
System.
out.
println(
"main thread sequence of "
+
j
+
",loop of "
+
i);
}
bShouldSub
=
true;
condition.
signal();
}
finally{
lock.
unlock();
}
}
}
}
------------- android培训、java培训、java学习型技术博客、期待与您交流! ------------
详情请查看:http://edu.csdn.net/