本帖最后由 a12366456 于 2015-7-27 15:21 编辑
使用Lock同步代码快的时候,开两个线程代码执行完,程序会终止。如果开启三个以上的线程,代码执行完,程序并不终止。使用synchronized没有这种现象,这是为何
- public class ThreadLock implements Runnable {
- private Count count;
- public ThreadLock(Count count) {
- this.setCount(count);
- }
- public ThreadLock() {
- // TODO Auto-generated constructor stub
- }
- @Override
- public void run() {
- while (count.getI()>0) {
- count.printCount();
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- Count count = new Count(20);
- new Thread(new ThreadLock(count), "线程1").start();
- new Thread(new ThreadLock(count), "线程2").start();
- new Thread(new ThreadLock(count), "线程3").start();
- new Thread(new ThreadLock(count), "线程4").start();
- }
- public Count getCount() {
- return count;
- }
- public void setCount(Count count) {
- this.count = count;
- }
- }
- class Count {
- private int i = 0;
- private Lock lock = new ReentrantLock();
- public Count(int i) {
- super();
- this.i = i;
- }
- public void printCount() {
- lock.lock();
- //synchronized (ThreadLock.class) {
- if (i > 0) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- System.out.println(Thread.currentThread().getName() + " i=" + i--);
- } finally {
- lock.unlock();
- }
- }
- // }
-
- }
- public int getI() {
- return i;
- }
- public void setI(int i) {
- this.i = i;
- }
- }
复制代码
|
|