线程阻塞工具类LockSupport+线程复用

比起Thread.suspend更加安全,比起object.wait不需要获得某个对象的锁,也不会抛出InterruptedException异常。

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class AccoutSync implements Runnable {

    public  static ReentrantLock lock=new ReentrantLock();
    public  static Condition condition=lock.newCondition();
   public static Object u=new Object();
    static  int i=0;
    @Override
    public void run() {

        synchronized (u) {
            while (i < 101) {



                    System.out.println(Thread.currentThread().getName() + " " + i);
                    LockSupport.park();
                    i++;


            }
        }
    }



    public static void  main(String[] args) throws InterruptedException {

        Thread t1=new Thread("T1");
        Thread.sleep(100);
        Thread t2=new Thread("T2");
        t1.start();
        t2.start();
        LockSupport.unpark(t1);
        LockSupport.unpark(t2);
        Thread.sleep(2000);



       t1.join();
        t2.join();


    }
}

线程池简单理解:创建线程变成了从线程池获得空闲线程,关闭线程变成了向池子归还线程。

【Executor】JDK对线程池的支持。

框架图如下:

线程阻塞工具类LockSupport+线程复用_第1张图片

        ExecutorService exec= Executors.newFixedThreadPool(10);//固定线程数量线程池
        Executors.newCachedThreadPool();//根据实际情况调整的线程数量线程池
        Executors.newSingleThreadExecutor();//只有一个线程数量线程池
        Executors.newSingleThreadScheduledExecutor();//返回对象线程数量线程池
        Executors.newScheduledThreadPool(10);//返回对象,可以指定线程数量线程池

深度了解可以看官方原版

你可能感兴趣的:(JAVA)