1、Lock

  • Lock类同样可达到synchronized效果,且在使用上比synchronized更加灵活
  • Lock lock = new ReentrantLock();
  • 加锁:lock.lock();
  • 解锁:lock.unlock(); ``` public class Main { public static void main(String[] args) {
  1. MyRunnable runnable = new MyRunnable();
  2. new Thread(runnable, "SyncThread1").start();
  3. new Thread(runnable, "SyncThread2").start();
  4. /**
  5. SyncThread1:0
  6. SyncThread1:1
  7. SyncThread1:2
  8. SyncThread1:3
  9. SyncThread1:4
  10. SyncThread2:5
  11. SyncThread2:6
  12. SyncThread2:7
  13. SyncThread2:8
  14. SyncThread2:9
  15. */
  16. }
  17. static class MyRunnable implements Runnable {
  18. public static int count;
  19. private Lock lock = new ReentrantLock();
  20. public MyRunnable() {
  21. count = 0;
  22. }
  23. public void run() {
  24. // 此处锁的是MyRunnable对象
  25. lock.lock();
  26. try {
  27. for (int i = 0; i < 5; i++) {
  28. try {
  29. System.out.println(Thread.currentThread().getName() + ":" + (count++));
  30. Thread.sleep(100);
  31. } catch (InterruptedException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. } finally {
  36. lock.unlock();
  37. }
  38. }
  39. }

} ```