标签:
void show(){ Synchronized(this){ wait() //可以同时有三个线程在此等待。只有拿到锁后,才能继续向下运行 } } void start(){ notifyAll(); //唤醒后,三个线程都具备了执行资格,但是并不是都具备执行权。 }
public class Interrupted { public static void main(String[] args) { Task t=new Task(); Thread t1=new Thread(t); t1.start(); } } class Task implements Runnable { @Override public void run() { for (int i=0;i<50;i++) { if(i==30) Thread.currentThread().interrupt(); System.out.println(Thread.currentThread().isInterrupted()+""+i); } } }
输出:
false0
false1
false2
false3
false4
false5
false6
false7
false8
false9
false10
false11
false12
false13
false14
false15
false16
false17
false18
false19
false20
false21
false22
false23
false24
false25
false26
false27
false28
false29
true30
true31
true32
true33
true34
true35
true36
true37
true38
true39
true40
true41
true42
true43
true44
true45
true46
true47
true48
true49
public static final ThreadLocal<SimpleDateForamt> dateFormat=new ThreadLocal<SimpleDateForamt>() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }
private ReentrantReadWriteLock rwl=new ReentrantReadWriteLock(); Private Lock readLock=rwl.readLock(); //读取操作共享,排斥写操作 private Lock writeLock=rwl.writeLock(); //排斥所有其他操作
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * Created by Administrator on 2016/6/30. */ public class Exercise { public static void main(String[] args) { FutureTask<Integer> task=new FutureTask<Integer>(new Counter()); //包装Callable Thread t=new Thread(task); t.start(); //这是Runnable接口的特性 try { System.out.println(task.get()); //这是Future接口的特性 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } class Counter implements Callable<Integer> { int sum; @Override public Integer call() throws Exception { for (int i=0;i<100;i++) { sum+=i; } return sum; } }
// public static ExecutorService newFixedThreadPool(int nThreads) ExecutorService pool = Executors.newFixedThreadPool(2); // 可以执行Runnable对象或者Callable对象代表的线程 Future fu1=pool.submit(new MyRunnable()); Future fu2=pool.submit(new MyCallable()); fu1.cancel();//取消该任务 System.out.println(fu2.get());//获取Callable对象的运行结果 //结束线程池 pool.shutdown();
标签:
原文地址:http://www.cnblogs.com/hlhdidi/p/5631485.html