编程第四十六、四十七天

 
  
synchronized关键字用于监视方法

1.构造一个计数器类Counter ,这个计数器可能会被多个线程访问,需要对其中的add()方法进行同步

public class Counter {
  long count = 0;
  //同步实例方法
  public synchronized void add() {
         count++;
         try {
              Thread. sleep(100);
        } catch (InterruptedException e) {
               e.printStackTrace();
        }
        System. out.println(Thread. currentThread().getName() + "--" + count);
  }
}

2.构造计数器线程类CounterThread 来访问计数器对象的add()方法

public class CounterThread extends Thread {
  protected Counter counter = null;
  public CounterThread( Counter counter) {
         this. counter = counter;
  }
  public void run() {
         //用多个线程调用同步实例方法
         for ( int i = 0; i < 5; i++) {
               counter.add();
        }
  }
}

3.构造一个CounterExample,用两个线程来同时访问一个对象实例

public class CounterExample {
  public static void main(String[] args) {       
        //构造一个含同步方法的对象实例   
        Counter counter = new Counter();
        Thread threadA = new CounterThread( counter);
        Thread threadB = new CounterThread( counter);
         threadA.start();
         threadB.start();
  }
}
运行结果:
Thread-0--1
Thread-1--2
Thread-0--3
Thread-1--4
Thread-1--5
Thread-0--6
Thread-1--7
Thread-1--8
Thread-0--9
Thread-0--10

你可能感兴趣的:(编程第四十六、四十七天)