天天看点

java多线程锁

在上一节中,

public
  
 class
  ThreadDemo 
 implements
  Runnable {

     
 class
  Student {

         
 private
  
 int
  age 
 =
  
 0
 ;

         
 public
  
 int
  getAge() {
             
 return
  age;
         }

         
 public
  
 void
  setAge(
 int
  age) {
             
 this
 .age 
 =
  age;
         }
     }
     Student student 
 =
  
 new
  Student();
     
 int
  count 
 =
  
 0
 ;

     
 public
  
 static
  
 void
  main(String[] args) {
         ThreadDemo td 
 =
  
 new
  ThreadDemo();
         Thread t1 
 =
  
 new
  Thread(td, 
 "
 a
 "
 );
         Thread t2 
 =
  
 new
  Thread(td, 
 "
 b
 "
 );
         Thread t3 
 =
  
 new
  Thread(td, 
 "
 c
 "
 );
         t1.start();
         t2.start();
         t3.start();
     }

     
 public
  
 void
  run() {
         accessStudent();
     }

     
 public
  
 void
  accessStudent() {
         String currentThreadName 
 =
  Thread.currentThread().getName();
         System.out.println(currentThreadName 
 +
  
 "
  is running!
 "
 );
         
 synchronized
  (
 this
 ) {
 //
 (1)使用同一个ThreadDemo对象作为同步锁
 

             System.out.println(currentThreadName 
 +
  
 "
  got lock1@Step1!
 "
 );
             
 try
  {
                 count
 ++
 ;
                 Thread.sleep(
 5000
 );
             } 
 catch
  (Exception e) {
                 e.printStackTrace();
             } 
 finally
  {
                 System.out.println(currentThreadName 
 +
  
 "
  first Reading count:
 "
  
 +
  count);
             }

         }
        
         System.out.println(currentThreadName 
 +
  
 "
  release lock1@Step1!
 "
 );

         
 synchronized
  (
 this
 ) {
 //
 (2)使用同一个ThreadDemo对象作为同步锁
 

             System.out.println(currentThreadName 
 +
  
 "
  got lock2@Step2!
 "
 );
             
 try
  {
                 Random random 
 =
  
 new
  Random();
                 
 int
  age 
 =
  random.nextInt(
 100
 );
                 System.out.println(
 "
 thread 
 "
  
 +
  currentThreadName 
 +
  
 "
  set age to:
 "
  
 +
  age);

                 
 this
 .student.setAge(age);

                 System.out.println(
 "
 thread 
 "
  
 +
  currentThreadName 
 +
  
 "
  first  read age is:
 "
  
 +
  
 this
 .student.getAge());

                 Thread.sleep(
 5000
 );
             } 
 catch
  (Exception ex) {
                 ex.printStackTrace();
             } 
 finally
 {
                 System.out.println(
 "
 thread 
 "
  
 +
  currentThreadName 
 +
  
 "
  second read age is:
 "
  
 +
  
 this
 .student.getAge());
             }

         }
         System.out.println(currentThreadName 
 +
  
 "
  release lock2@Step2!
 "
 );
     }
 }