2.多线程(同步类级别锁)

多个线程多个锁

    1.多个线程,每个线程都可以去拿到自己制定的锁(object) ,分别获取锁后,执行 synchronized 方法。

    2. synchronized 拿到的锁都是对象锁,而不是把一段代码、方法的锁,多个线程就次有该方法的对象锁。2个对象,线程获取就是2个对象不同的锁(互不影响)。

    3.有一种情况就是相同的锁,就是在该 synchronized 方法是用static关键字,表示锁定 class 类,类级别的锁独占l class 类。


    

  1. /**
  2. * Created by liudan on 2017/5/29.
  3. */
  4. public class MyThread2 extends Thread {
  5. private static int num = 0;
  6. public static synchronized void printNum(String str) {
  7. try {
  8. if (str.equals("a")) {
  9. num = 1000;
  10. System.err.println("thread -> A over");
  11. Thread.sleep(1000);
  12. } else if (str.equals("b")) {
  13. num = 200;
  14. System.err.println("thread -> B over");
  15. }
  16. System.err.println("str:" + str + "\tnum:" + num);
  17. } catch (InterruptedException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. public static void main(String[] args) {
  22. //2个不同的对象,只能new一次
  23. final MyThread2 n1 = new MyThread2();
  24. final MyThread2 n2 = new MyThread2();
  25. Thread t1 = new Thread(new Runnable() {
  26. @Override
  27. public void run() {
  28. n1.printNum("a");
  29. }
  30. });
  31. Thread t2 = new Thread(new Runnable() {
  32. @Override
  33. public void run() {
  34. n2.printNum("b");
  35. }
  36. });
  37. t1.start();
  38. t2.start();
  39. }
  40. }
  41. 输出

thread -> B over str:b num:200 thread -> A over str:a num:1000

 

posted @ 2017-08-10 02:09  逍遥叹!!  阅读(229)  评论(0编辑  收藏  举报