Java线程:新特征-有返回值的线程
在Java5之前,线程是没有返回值的,常常为了“有”返回值,破费周折,而且代码很不好写。或者干脆绕过这道坎,走别的路了。
现在Java终于有可返回值的任务(也可以叫做线程)了。
可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。
执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了。
下面是个很简单的例子:
import java.util.concurrent.*;
/**
* Java线程:有返回值的线程
*
* @author Administrator 2009-11-5 0:41:50
*/
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//创建两个有返回值的任务
Callable c1 = new MyCallable( "A");
Callable c2 = new MyCallable( "B");
//执行任务并获取Future对象
Future f1 = pool.submit(c1);
Future f2 = pool.submit(c2);
//从Future对象上获取任务的返回值,并输出到控制台
System.out.println( ">>>"+f1.get().toString());
System.out.println( ">>>"+f2.get().toString());
//关闭线程池
pool.shutdown();
}
}
class MyCallable implements Callable{
private String oid;
MyCallable(String oid) {
this.oid = oid;
}
@Override
public Object call() throws Exception {
return oid+ "任务返回的内容";
}
}
/**
* Java线程:有返回值的线程
*
* @author Administrator 2009-11-5 0:41:50
*/
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//创建两个有返回值的任务
Callable c1 = new MyCallable( "A");
Callable c2 = new MyCallable( "B");
//执行任务并获取Future对象
Future f1 = pool.submit(c1);
Future f2 = pool.submit(c2);
//从Future对象上获取任务的返回值,并输出到控制台
System.out.println( ">>>"+f1.get().toString());
System.out.println( ">>>"+f2.get().toString());
//关闭线程池
pool.shutdown();
}
}
class MyCallable implements Callable{
private String oid;
MyCallable(String oid) {
this.oid = oid;
}
@Override
public Object call() throws Exception {
return oid+ "任务返回的内容";
}
}
>>>A任务返回的内容
>>>B任务返回的内容
Process finished with exit code 0
>>>B任务返回的内容
Process finished with exit code 0
非常的简单,要深入了解还需要看Callable和Future接口的API啊。
Java线程:新特征-锁(上)
在Java5中,专门提供了锁对象,利用锁可以方便的实现资源的封锁,用来控制对竞争资源并发访问的控制,这些内容主要集中在java.util.concurrent.locks 包下面,里面有三个重要的接口Condition、Lock、ReadWriteLock。
有关锁的介绍,API文档解说很多,看得很烦,还是看个例子再看文档比较容易理解。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Java线程:锁
*
* @author leizhimin 2009-11-5 10:57:29
*/
public class Test {
public static void main(String[] args) {
//创建并发访问的账户
MyCount myCount = new MyCount( "95599200901215522", 10000);
//创建一个锁对象
Lock lock = new ReentrantLock();
//创建一个线程池
ExecutorService pool = Executors.newCachedThreadPool();
//创建一些并发访问用户,一个信用卡,存的存,取的取,好热闹啊
User u1 = new User( "张三", myCount, -4000, lock);
User u2 = new User( "张三他爹", myCount, 6000, lock);
User u3 = new User( "张三他弟", myCount, -8000, lock);
User u4 = new User( "张三", myCount, 800, lock);
//在线程池中执行各个用户的操作
pool.execute(u1);
pool.execute(u2);
pool.execute(u3);
pool.execute(u4);
//关闭线程池
pool.shutdown();
}
}
/**
* 信用卡的用户
*/
class User implements Runnable {
private String name; //用户名
private MyCount myCount; //所要操作的账户
private int iocash; //操作的金额,当然有正负之分了
private Lock myLock; //执行操作所需的锁对象
User(String name, MyCount myCount, int iocash, Lock myLock) {
this.name = name;
this.myCount = myCount;
this.iocash = iocash;
this.myLock = myLock;
}
public void run() {
//获取锁
myLock.lock();
//执行现金业务
System.out.println(name + "正在操作" + myCount + "账户,金额为" + iocash + ",当前金额为" + myCount.getCash());
myCount.setCash(myCount.getCash() + iocash);
System.out.println(name + "操作" + myCount + "账户成功,金额为" + iocash + ",当前金额为" + myCount.getCash());
//释放锁,否则别的线程没有机会执行了
myLock.unlock();
}
}
/**
* 信用卡账户,可随意透支
*/
class MyCount {
private String oid; //账号
private int cash; //账户余额
MyCount(String oid, int cash) {
this.oid = oid;
this.cash = cash;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public int getCash() {
return cash;
}
public void setCash( int cash) {
this.cash = cash;
}
@Override
public String toString() {
return "MyCount{" +
"oid='" + oid + '\'' +
", cash=" + cash +
'}';
}
}
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Java线程:锁
*
* @author leizhimin 2009-11-5 10:57:29
*/
public class Test {
public static void main(String[] args) {
//创建并发访问的账户
MyCount myCount = new MyCount( "95599200901215522", 10000);
//创建一个锁对象
Lock lock = new ReentrantLock();
//创建一个线程池
ExecutorService pool = Executors.newCachedThreadPool();
//创建一些并发访问用户,一个信用卡,存的存,取的取,好热闹啊
User u1 = new User( "张三", myCount, -4000, lock);
User u2 = new User( "张三他爹", myCount, 6000, lock);
User u3 = new User( "张三他弟", myCount, -8000, lock);
User u4 = new User( "张三", myCount, 800, lock);
//在线程池中执行各个用户的操作
pool.execute(u1);
pool.execute(u2);
pool.execute(u3);
pool.execute(u4);
//关闭线程池
pool.shutdown();
}
}
/**
* 信用卡的用户
*/
class User implements Runnable {
private String name; //用户名
private MyCount myCount; //所要操作的账户
private int iocash; //操作的金额,当然有正负之分了
private Lock myLock; //执行操作所需的锁对象
User(String name, MyCount myCount, int iocash, Lock myLock) {
this.name = name;
this.myCount = myCount;
this.iocash = iocash;
this.myLock = myLock;
}
public void run() {
//获取锁
myLock.lock();
//执行现金业务
System.out.println(name + "正在操作" + myCount + "账户,金额为" + iocash + ",当前金额为" + myCount.getCash());
myCount.setCash(myCount.getCash() + iocash);
System.out.println(name + "操作" + myCount + "账户成功,金额为" + iocash + ",当前金额为" + myCount.getCash());
//释放锁,否则别的线程没有机会执行了
myLock.unlock();
}
}
/**
* 信用卡账户,可随意透支
*/
class MyCount {
private String oid; //账号
private int cash; //账户余额
MyCount(String oid, int cash) {
this.oid = oid;
this.cash = cash;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public int getCash() {
return cash;
}
public void setCash( int cash) {
this.cash = cash;
}
@Override
public String toString() {
return "MyCount{" +
"oid='" + oid + '\'' +
", cash=" + cash +
'}';
}
}
张三正在操作MyCount{oid='95599200901215522', cash=10000}账户,金额为-4000,当前金额为10000
张三操作MyCount{oid='95599200901215522', cash=6000}账户成功,金额为-4000,当前金额为6000
张三他爹正在操作MyCount{oid='95599200901215522', cash=6000}账户,金额为6000,当前金额为6000
张三他爹操作MyCount{oid='95599200901215522', cash=12000}账户成功,金额为6000,当前金额为12000
张三他弟正在操作MyCount{oid='95599200901215522', cash=12000}账户,金额为-8000,当前金额为12000
张三他弟操作MyCount{oid='95599200901215522', cash=4000}账户成功,金额为-8000,当前金额为4000
张三正在操作MyCount{oid='95599200901215522', cash=4000}账户,金额为800,当前金额为4000
张三操作MyCount{oid='95599200901215522', cash=4800}账户成功,金额为800,当前金额为4800
Process finished with exit code 0
张三操作MyCount{oid='95599200901215522', cash=6000}账户成功,金额为-4000,当前金额为6000
张三他爹正在操作MyCount{oid='95599200901215522', cash=6000}账户,金额为6000,当前金额为6000
张三他爹操作MyCount{oid='95599200901215522', cash=12000}账户成功,金额为6000,当前金额为12000
张三他弟正在操作MyCount{oid='95599200901215522', cash=12000}账户,金额为-8000,当前金额为12000
张三他弟操作MyCount{oid='95599200901215522', cash=4000}账户成功,金额为-8000,当前金额为4000
张三正在操作MyCount{oid='95599200901215522', cash=4000}账户,金额为800,当前金额为4000
张三操作MyCount{oid='95599200901215522', cash=4800}账户成功,金额为800,当前金额为4800
Process finished with exit code 0
从上面的输出可以看到,利用锁对象太方便了,比直接在某个不知情的对象上用锁清晰多了。
但一定要注意的是,在获取了锁对象后,用完后应该尽快释放锁,以便别的等待该锁的线程有机会去执行。
Java线程:新特征-锁(下)
在上文中提到了Lock接口以及对象,使用它,很优雅的控制了竞争资源的安全访问,但是这种锁不区分读写,称这种锁为普通锁。为了提高性能,Java提供了读写锁,在读的地方使用读锁,在写的地方使用写锁,灵活控制,在一定程度上提高了程序的执行效率。
Java中读写锁有个接口java.util.concurrent.locks.ReadWriteLock,也有具体的实现ReentrantReadWriteLock,详细的API可以查看JavaAPI文档。
下面这个例子是在文例子的基础上,将普通锁改为读写锁,并添加账户余额查询的功能,代码如下:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Java线程:锁
*
* @author leizhimin 2009-11-5 10:57:29
*/
public class Test {
public static void main(String[] args) {
//创建并发访问的账户
MyCount myCount = new MyCount( "95599200901215522", 10000);
//创建一个锁对象
ReadWriteLock lock = new ReentrantReadWriteLock( false);
//创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//创建一些并发访问用户,一个信用卡,存的存,取的取,好热闹啊
User u1 = new User( "张三", myCount, -4000, lock, false);
User u2 = new User( "张三他爹", myCount, 6000, lock, false);
User u3 = new User( "张三他弟", myCount, -8000, lock, false);
User u4 = new User( "张三", myCount, 800, lock, false);
User u5 = new User( "张三他爹", myCount, 0, lock, true);
//在线程池中执行各个用户的操作
pool.execute(u1);
pool.execute(u2);
pool.execute(u3);
pool.execute(u4);
pool.execute(u5);
//关闭线程池
pool.shutdown();
}
}
/**
* 信用卡的用户
*/
class User implements Runnable {
private String name; //用户名
private MyCount myCount; //所要操作的账户
private int iocash; //操作的金额,当然有正负之分了
private ReadWriteLock myLock; //执行操作所需的锁对象
private boolean ischeck; //是否查询
User(String name, MyCount myCount, int iocash, ReadWriteLock myLock, boolean ischeck) {
this.name = name;
this.myCount = myCount;
this.iocash = iocash;
this.myLock = myLock;
this.ischeck = ischeck;
}
public void run() {
if (ischeck) {
//获取读锁
myLock.readLock().lock();
System.out.println( "读:" + name + "正在查询" + myCount + "账户,当前金额为" + myCount.getCash());
//释放读锁
myLock.readLock().unlock();
} else {
//获取写锁
myLock.writeLock().lock();
//执行现金业务
System.out.println( "写:" + name + "正在操作" + myCount + "账户,金额为" + iocash + ",当前金额为" + myCount.getCash());
myCount.setCash(myCount.getCash() + iocash);
System.out.println( "写:" + name + "操作" + myCount + "账户成功,金额为" + iocash + ",当前金额为" + myCount.getCash());
//释放写锁
myLock.writeLock().unlock();
}
}
}
/**
* 信用卡账户,可随意透支
*/
class MyCount {
private String oid; //账号
private int cash; //账户余额
MyCount(String oid, int cash) {
this.oid = oid;
this.cash = cash;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public int getCash() {
return cash;
}
public void setCash( int cash) {
this.cash = cash;
}
@Override
public String toString() {
return "MyCount{" +
"oid='" + oid + '\'' +
", cash=" + cash +
'}';
}
}
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Java线程:锁
*
* @author leizhimin 2009-11-5 10:57:29
*/
public class Test {
public static void main(String[] args) {
//创建并发访问的账户
MyCount myCount = new MyCount( "95599200901215522", 10000);
//创建一个锁对象
ReadWriteLock lock = new ReentrantReadWriteLock( false);
//创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//创建一些并发访问用户,一个信用卡,存的存,取的取,好热闹啊
User u1 = new User( "张三", myCount, -4000, lock, false);
User u2 = new User( "张三他爹", myCount, 6000, lock, false);
User u3 = new User( "张三他弟", myCount, -8000, lock, false);
User u4 = new User( "张三", myCount, 800, lock, false);
User u5 = new User( "张三他爹", myCount, 0, lock, true);
//在线程池中执行各个用户的操作
pool.execute(u1);
pool.execute(u2);
pool.execute(u3);
pool.execute(u4);
pool.execute(u5);
//关闭线程池
pool.shutdown();
}
}
/**
* 信用卡的用户
*/
class User implements Runnable {
private String name; //用户名
private MyCount myCount; //所要操作的账户
private int iocash; //操作的金额,当然有正负之分了
private ReadWriteLock myLock; //执行操作所需的锁对象
private boolean ischeck; //是否查询
User(String name, MyCount myCount, int iocash, ReadWriteLock myLock, boolean ischeck) {
this.name = name;
this.myCount = myCount;
this.iocash = iocash;
this.myLock = myLock;
this.ischeck = ischeck;
}
public void run() {
if (ischeck) {
//获取读锁
myLock.readLock().lock();
System.out.println( "读:" + name + "正在查询" + myCount + "账户,当前金额为" + myCount.getCash());
//释放读锁
myLock.readLock().unlock();
} else {
//获取写锁
myLock.writeLock().lock();
//执行现金业务
System.out.println( "写:" + name + "正在操作" + myCount + "账户,金额为" + iocash + ",当前金额为" + myCount.getCash());
myCount.setCash(myCount.getCash() + iocash);
System.out.println( "写:" + name + "操作" + myCount + "账户成功,金额为" + iocash + ",当前金额为" + myCount.getCash());
//释放写锁
myLock.writeLock().unlock();
}
}
}
/**
* 信用卡账户,可随意透支
*/
class MyCount {
private String oid; //账号
private int cash; //账户余额
MyCount(String oid, int cash) {
this.oid = oid;
this.cash = cash;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public int getCash() {
return cash;
}
public void setCash( int cash) {
this.cash = cash;
}
@Override
public String toString() {
return "MyCount{" +
"oid='" + oid + '\'' +
", cash=" + cash +
'}';
}
}
写:张三正在操作MyCount{oid='95599200901215522', cash=10000}账户,金额为-4000,当前金额为10000
写:张三操作MyCount{oid='95599200901215522', cash=6000}账户成功,金额为-4000,当前金额为6000
写:张三他弟正在操作MyCount{oid='95599200901215522', cash=6000}账户,金额为-8000,当前金额为6000
写:张三他弟操作MyCount{oid='95599200901215522', cash=-2000}账户成功,金额为-8000,当前金额为-2000
写:张三正在操作MyCount{oid='95599200901215522', cash=-2000}账户,金额为800,当前金额为-2000
写:张三操作MyCount{oid='95599200901215522', cash=-1200}账户成功,金额为800,当前金额为-1200
读:张三他爹正在查询MyCount{oid='95599200901215522', cash=-1200}账户,当前金额为-1200
写:张三他爹正在操作MyCount{oid='95599200901215522', cash=-1200}账户,金额为6000,当前金额为-1200
写:张三他爹操作MyCount{oid='95599200901215522', cash=4800}账户成功,金额为6000,当前金额为4800
Process finished with exit code 0
写:张三操作MyCount{oid='95599200901215522', cash=6000}账户成功,金额为-4000,当前金额为6000
写:张三他弟正在操作MyCount{oid='95599200901215522', cash=6000}账户,金额为-8000,当前金额为6000
写:张三他弟操作MyCount{oid='95599200901215522', cash=-2000}账户成功,金额为-8000,当前金额为-2000
写:张三正在操作MyCount{oid='95599200901215522', cash=-2000}账户,金额为800,当前金额为-2000
写:张三操作MyCount{oid='95599200901215522', cash=-1200}账户成功,金额为800,当前金额为-1200
读:张三他爹正在查询MyCount{oid='95599200901215522', cash=-1200}账户,当前金额为-1200
写:张三他爹正在操作MyCount{oid='95599200901215522', cash=-1200}账户,金额为6000,当前金额为-1200
写:张三他爹操作MyCount{oid='95599200901215522', cash=4800}账户成功,金额为6000,当前金额为4800
Process finished with exit code 0
在实际开发中,最好在能用读写锁的情况下使用读写锁,而不要用普通锁,以求更好的性能。