class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System. out .println("------->Callable" );
return new Random().nextInt(50);
}
}
public class Demo0 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyThread myThread = new MyThread();
//因为这里的FutureTask实现了runnable接口,所以可以把FutureTask提交给Executor执行
FutureTask futureTask = new FutureTask(myThread);
new Thread(futureTask).start();
//可以通过FutureTask的get()方法来获取执行线程得到的返回值
Integer result = (Integer)futureTask.get();
System. out .println(result);
}
}
-
从上面代码可以得出,实现callable接口我们可以获得线程的执行结果,并且得到线程执行过程中的异常信息。
-
生产者,消费者实例
//共享数据的封装
class ShareData01{
private int number =0;
Lock lock = new ReentrantLock();
Condition condtion = lock.newCondition();
public void increament() throws InterruptedException{
lock.lock();
try {
//对于某一个参数的版本,实现中断和虚假唤醒是可能的,而且wait()方法应始终在循环中使用,这样即使循环中
//有多个阻塞状态的线程,当全部唤醒后,也只会有一个执行此方法
while (number !=0){
condtion.await(); //this.wait()
}
++ number;
System. out .println(Thread.currentThread().getName()+ ":" +number );
condtion.signalAll(); //this.notify()
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void decreament() throws InterruptedException{
lock.lock();
try {
while (number ==0){
condtion.await();
}
-- number;
System. out .println(Thread.currentThread().getName()+ ":" +number );
condtion.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
//四个线程的生产者,消费者实例
public class Demo02 {
public static void main(String[] args) {
final ShareData01 shareData = new ShareData01();
new Thread(new Runnable(){
@Override
public void run() {
for (int i = 0; i <10; i++) {
try {
Thread. sleep(1000);
shareData.increament();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "AA" ).start();
new Thread(new Runnable(){
@Override
public void run() {
for (int i = 0; i <10; i++) {
try {
Thread. sleep(1000);
shareData.increament();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, "BB" ).start();
new Thread(new Runnable(){
@Override
public void run() {
for (int i = 0; i <10; i++) {
try {
Thread. sleep(1000);
shareData.decreament();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, "CC" ).start();
new Thread(new Runnable(){
@Override
public void run() {
for (int i = 0; i <10; i++) {
try {
Thread. sleep(1000);
shareData.decreament();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, "DD" ).start();
}
}