日期:2014-05-20 浏览次数:20829 次
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class Demo { private int i = 100; int setI(int y) { System.out.println("减去" + y); return i = i - y; } int getI() { return i; } } public class SynchronrizedTest implements Runnable { Lock lock = new ReentrantLock(); private Demo demo = new Demo(); public static void main(String[] args) { SynchronrizedTest test1 = new SynchronrizedTest(); Thread thread1 = new Thread(test1, "线程1"); Thread thread2 = new Thread(test1, "线程2"); thread1.start(); thread2.start(); } public void run() { for (int i = 0; i < 5; i++) { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } lock.lock(); System.out.println(Thread.currentThread().getName() + "操作之前: " + demo.getI()); this.setI(10); System.out.println(Thread.currentThread().getName() + "操作之后: " + demo.getI()); System.out.println(); lock.unlock(); } } int setI(int y) { return demo.setI(y); } }
------解决方案--------------------