区别:
总结:
public static final Object OBJ = new Object(); public void show() { try { super.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { Runnable runnable = () -> { synchronized (OBJ) { System.out.println("线程【" + Thread.currentThread().getName() + "】正在执行..."); // 阻塞 LockSupport.park("我被阻塞了..."); if(Thread.currentThread().isInterrupted()){ System.out.println("被中断了..."); } System.out.println("继续执行..."); } }; Thread t1 = new Thread(runnable,"线程一"); Thread t2 = new Thread(runnable,"线程二"); t1.start(); Thread.sleep(1000); System.out.println(LockSupport.getBlocker(t1)); t2.start(); Thread.sleep(3000); // 线程中断 t1.interrupt(); // 把t2唤醒 LockSupport.unpark(t2); t1.join(); t2.join(); } }
public void show() { Lock lock = new Lock() { @Override public void lock() { } @Override public void lockInterruptibly() throws InterruptedException { } @Override public boolean tryLock() { return false; } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return false; } @Override public void unlock() { } @Override public Condition newCondition() { return null; } }; // 加锁 lock.lock(); try { // 正常处理业务逻辑 System.out.println(); }catch (Exception e){ // 当出现异常的解决方案 }finally { // 释放资源,关闭连接,关闭输入输出流 // 手动释放锁 lock.unlock(); } } public void info() { Lock lock = new Lock() { @Override public void lock() { } @Override public void lockInterruptibly() throws InterruptedException { } @Override public boolean tryLock() { return false; } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return false; } @Override public void unlock() { } @Override public Condition newCondition() { return null; } }; // 如果拿到了锁 if(lock.tryLock()){ try { // 正常处理业务逻辑 }catch (Exception e){ // 当出现异常的解决方案 }finally { // 释放资源,关闭连接,关闭输入输出流 // 手动释放锁 lock.unlock(); } }else { // 如果没有拿到锁,则直接做另外的事情 } } }
synchronized和Lock的区别:
class Ticket implements Runnable { private static final ReentrantLock lock = new ReentrantLock(); private static Integer count = 100; String name; public Ticket(String name) { this.name = name; } @Override public void run() { while(Ticket.count > 0){ lock.lock(); try { try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } if(count > 0){ System.out.println(name + "正在卖票,剩余:" + count + "张!"); count--; // count = count - 1; } }finally { lock.unlock(); } } } } public class Ch03 { public static void main(String[] args) { Ticket t1 = new Ticket("窗口一"); Ticket t2 = new Ticket("窗口二"); Ticket t3 = new Ticket("窗口三"); new Thread(t1).start(); new Thread(t2).start(); new Thread(t3).start(); } }
ReentrantReadWriteLock:读写锁
private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private static int count = 1; public static void main(String[] args) { Runnable read = () -> { // 创建了一个读锁 ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); readLock.lock(); try { Thread.sleep(2000); System.out.println("我在读数据:" + count); } catch (InterruptedException e) { e.printStackTrace(); }finally { readLock.unlock(); } }; Runnable write = () -> { // 创建了一个写锁 ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); writeLock.lock(); try { Thread.sleep(2000); System.out.println("我在写数据:" + count++); } catch (InterruptedException e) { e.printStackTrace(); } finally { writeLock.unlock(); } }; for (int i = 0; i < 100; i++) { Random random = new Random(); int flag = random.nextInt(100); System.out.println("生成的随机整数:" + flag); if(flag > 20){ new Thread(read).start(); }else { new Thread(write).start(); } } } }
synchronized是由C语言实现的,只能作为关键字来使用
java提供了一些并发的编程的包,底层的实现原理cas和aqs
并发编程三大特性:
1.原子性:原子操作可以是一个步骤,也可以是多个步骤,但是顺序不能乱,也不可以被切割只执行其中的一部分,将整个操作视为一个整体。原子性不仅仅是多行代码,也可能是多条指令。
2.可见性
3.有序性
synchronized lock:可以保证原子性、可见性、有序性。
CAS:compare and swap,比较并交换。JDK11改成了compare and set。
思路:就是给一个元素赋值的时候,先看看内存里的那个值到底变没变。
AQS:抽象队列同步器,用来解决线程同步执行的问题。它是一个双向链表
java.util.concurrent.atomic下
JUC并发编程包
1.原子类Atomic
基本类型
AtomicInteger:整型原子类
AtomicLong:长整型原子类
AtomicBoolean:布尔型原子类
数组类型
AtomicLongArray:长整型数组原子类
AtomicIntegerArray:整型数组原子类
AtomicReference
public class Ch06 { private static AtomicInteger adder = new AtomicInteger(); public static void main(String[] args) throws InterruptedException { int a = 10; for (int i = 0; i < 1000; i++) { Thread thread = new Thread(() -> { adder.getAndIncrement(); }); thread.start(); // 阻塞 thread.join(); } System.out.println("a:" + a); System.out.println("aaa:" + adder.get()); }
为什么要使用线程池
JDK自带的四种线程池通过Executors提供的
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
参数的意义(重要):
常见的工作队列
线程池提供了四种拒绝策略:
public class Ch01 { public static void main(String[] args) { ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); Runnable taskOne = () -> { System.out.println(Thread.currentThread().getName() + "taskOne..."); }; ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10); ExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10); ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); for (int i = 0; i < 40; i++) { fixedThreadPool.submit(taskOne); } } }
自定义线程池
public class Ch02 { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; Ch02(String name){ SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = name + "-" + poolNumber.getAndIncrement() + "-thread-"; } Ch02(){ this("default"); } public Thread newThread(Runnable r){ // 就是在创建线程 Thread t = new Thread(group,r,namePrefix + threadNumber.getAndIncrement(),0); if(t.isDaemon()){ t.setDaemon(false); } if(t.getPriority() != Thread.NORM_PRIORITY){ t.setPriority(Thread.NORM_PRIORITY); } return t; } public static void main(String[] args) { Ch02 ch02 = new Ch02(); ch02.newThread(()->{ System.out.println("自定义线程池创建的线程..."); }).start(); } }