/** * 1、建立执行线程的方式三:实现Callable接口。相较于实现Runnable接口方式,方法能够有返回值,而且能够抛出异常 * 2、callable 须要FutureTask实现类的支持。用于接受运算结果。FutureTask是Future接口的实现类。 * * 线程执行完以后才会执行result.get 能够当作闭锁看 */ public class TestCallable { public static void main(String[] args) { ThreadDemo td = new ThreadDemo(); FutureTask<Integer> result = new FutureTask<>(td); new Thread(result).start(); //接受thread运算后的结构 try { Integer sum= result.get(); System.out.println(sum); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } class ThreadDemo implements Callable<Integer> { @Override public Integer call() throws Exception { int sum=0; for(int i=0;i<=100;i++){ sum+=i; } return sum; } }
Lock:同步锁 安全
用于解决多线程安全问题的方式:多线程
1 同步代码块ide
2 不一样方法spa
3 同步锁(更加灵活的方式)
线程
/** * 显示的锁 使用lock方法上锁 而且使用unlock方法解锁 * 要在方法中上锁和释放锁 方法必须执行 因此通常使用finally来释放锁 */ public class TestLock { public static void main(String[] args) { Ticket ticket = new Ticket(); new Thread(ticket,"win 1").start(); new Thread(ticket,"win 2").start(); new Thread(ticket,"win 3").start(); } } class Ticket implements Runnable{ private int tick=100; Lock lock = new ReentrantLock(); @Override public void run() { while(true){ lock.lock(); try{ if(tick>0){ try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"完成售票,余票为:"+--tick); } }finally { lock.unlock(); } } } }
ReentrantLock是Lock的实现类code
在finally中调用lock.unlockblog