package Thread; import java.util.concurrent.CopyOnWriteArrayList; public class TestJUC { public static void main(String[] args) { CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); for(int i = 0; i < 1000; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(list.size()); } }
package Thread; /* 死锁:多个线程相互抱着对方需要的资源,然后形成僵持 */ public class DeadLock { public static void main(String[] args) { Makeup g1 = new Makeup(0,"小红"); Makeup g2 = new Makeup(1,"小美"); g1.start(); g2.start(); } } class Lipstick{ } class Mirror{ } class Makeup extends Thread{ /* 资源只有一份,用static来保证只有一份 */ static Lipstick lipstick = new Lipstick(); static Mirror mirror = new Mirror(); /* 选择 */ int choice; /* 使用者 */ String name; Makeup(int choice, String name){ this.choice = choice; this.name = name; } public void run() { makeup(); } /* 互相持有对方的锁,就是需要拿到对方的资源 */ private void makeup() { if(choice == 0) { synchronized(lipstick){ System.out.println(this.name+"获得口红的锁"); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } synchronized(mirror){ System.out.println(this.name+"获得镜子的锁"); } } else { synchronized(mirror){ System.out.println(this.name+"获得镜子的锁"); try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } synchronized(lipstick){ System.out.println(this.name+"获得口红的锁"); } } } }
class A{ private final ReentrantLock lock = new ReeentrantLock(); public void m(){ lock.lock(); try{ //保证线程安全的代码; } finally{ lock.unlock(); //如果同步代码有异常,要将unlock()写入finally代码块 } } }
package Thread; import java.util.concurrent.locks.ReentrantLock; /* 测试Lock锁 */ public class TestLock { public static void main(String[] args) { TestLock2 lock = new TestLock2(); new Thread(lock).start(); new Thread(lock).start(); new Thread(lock).start(); } } class TestLock2 implements Runnable{ int ticketNums = 10; /* 定义Lock锁 */ private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { // TODO Auto-generated method stub try { /* 加锁 */ lock.lock(); while(true) { if(ticketNums>0) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(ticketNums--); } else { break; } } }finally { /* 解锁 */ lock.unlock(); } } }
synchronized与Lock的对比
Lock是显式锁(手动开启和关闭锁,别忘记关闭锁);synchronized是隐式锁,出了作用域自动释放
Lock只有代码块锁,synchronized有代码块锁和方法锁
使用Lock锁,JVM将花费较少的时间来调度线程,性能更好,并且具有更好的拓展性(提供更多子类)
优先使用顺序:
Lock>同步方法块(已经进入了方法体,分配了相应资源)>同步方法(在方法体之外)