标签:syn 加锁 线程 span nts out 进入 安全 java
1 package com.thread.gaoji; 2 3 import java.util.concurrent.locks.ReentrantLock; 4 5 //测试Lock锁 6 public class TestLock { 7 public static void main(String[] args) { 8 TestLock2 testLock2 = new TestLock2(); 9 10 new Thread(testLock2).start(); 11 new Thread(testLock2).start(); 12 new Thread(testLock2).start(); 13 } 14 } 15 16 class TestLock2 implements Runnable { 17 18 int ticketNums = 10; 19 20 //定以lock锁 21 private final ReentrantLock lock = new ReentrantLock(); 22 23 @Override 24 public void run() { 25 26 while (true) { 27 try { 28 lock.lock();//加锁 29 if (ticketNums > 0) { 30 try { 31 Thread.sleep(1000); 32 } catch (InterruptedException e) { 33 e.printStackTrace(); 34 } 35 System.out.println(ticketNums--); 36 } else { 37 break; 38 } 39 } finally { 40 //解锁 41 lock.unlock(); 42 } 43 } 44 } 45 } 46 47 结果: 48 10 49 9 50 8 51 7 52 6 53 5 54 4 55 3 56 2 57 1
1 class A { 2 private final ReentrantLock lock = new ReentrantLock(); 3 4 public void m() { 5 lock.lock(); 6 try { 7 //保证线程安全的代码; 8 } finally { 9 lock.unlock(); 10 //如果同步代码有异常,要将unlock()写入finally语句块 11 } 12 } 13 }
标签:syn 加锁 线程 span nts out 进入 安全 java
原文地址:https://www.cnblogs.com/duanfu/p/12260780.html