FutureTask类实现了RunnableFuture接口,其中两个构造器:
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW;
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW;
}
Callable接口和Runnable接口的不同:
Callable接口实现call()方法,而Runnable实现run()方法,而call()会返回计算结果值,而run()只是执行函数体。
其在jdk中定义
public interface Callable {
V call() throws Exception;
}
public interface Runnable {
public abstract void run();
}
volatile关键字的作用:
1.保证可见性,不保证原子性
2.禁止指令重排
即为了线程对共享变量值的修改,能够及时的被其他线程看到。
但是volatile 变量的同步性较差(有时它更简单并且开销更低),而且其使用也更容易出错,所以并不能完全保证正确
class Resource implements Runnable {
volatile public int i;
public Resource(int _i){
i = _i;
}
public void run(){
while(true){
if (i>0){
try{
Thread.sleep(200);
}
catch(Exception e){}
i--;
System.out.println(Thread.
currentThread().getName()+" "+i);
}
else{
System.out.println(Thread.
currentThread().getName());
break;
}
}
}}
public class TestSecurity{
public static void main(String[] args){
Resource m = new Resource(9);
Thread t1 = new Thread(m);
Thread t2 = new Thread(m);
t1.start();
t2.start();
}
}
此时就要使用Synchronized。
Java提供同步机制实现互斥:
volatile关键字, Synchronized,Lock接口
ReentrantLock类等来实现互斥。