Permalink
Browse files

use Lock class

  • Loading branch information...
1 parent 6703339 commit 49c28267b7309dc1ddea59ca03280f7c5be6ccd1 @wangdengwu committed Feb 27, 2012
@@ -1,5 +1,10 @@
-package study.wdw.thread;
+package study.wdw.thread.interrupt;
+/**
+ *
+ * @author wangdengwu
+ * @since 2012-2-27
+ */
public class JoinThread implements Runnable {
@Override
@@ -1,4 +1,4 @@
-package study.wdw.thread;
+package study.wdw.thread.interrupt;
/**
*
@@ -1,4 +1,4 @@
-package study.wdw.thread;
+package study.wdw.thread.interrupt;
/**
*
@@ -0,0 +1,37 @@
+package study.wdw.thread.lock;
+
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * 使用Lock代替synchronized
+ *
+ * @author wangdengwu
+ * @since 2012-2-27
+ */
+public class LockThread implements Runnable {
+ public int i = 0;
+ private Lock lock = new ReentrantLock();// 私有锁
+ private volatile boolean done = false;// 使用volatile标记可见性
+ @Override
+ public void run() {
+ while (!done) {
+ doMath();
+ }
+ }
+
+ // 此方法如果不同步则有可能使i不为0
+ public void doMath() {
+ try {
+ lock.lock();
+ i++;
+ i--;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void setDone() {
+ done = true;
+ }
+}
@@ -1,5 +1,8 @@
package study.wdw.thread;
+import study.wdw.thread.interrupt.JoinThread;
+import study.wdw.thread.interrupt.SleepThread;
+import study.wdw.thread.interrupt.WaitThread;
import junit.framework.TestCase;
/**
@@ -0,0 +1,23 @@
+package study.wdw.thread;
+
+import junit.framework.TestCase;
+import study.wdw.thread.lock.LockThread;
+
+/**
+ * 测试Lock
+ *
+ * @author wangdengwu
+ * @since 2012-2-27
+ */
+public class LockTest extends TestCase {
+ public void testLock() throws InterruptedException {
+ LockThread lockThread = new LockThread();
+ Thread thread1 = new Thread(lockThread);
+ Thread thread2 = new Thread(lockThread);
+ thread1.start();
+ thread2.start();
+ Thread.sleep(1000 * 60);
+ lockThread.setDone();
+ assertEquals(0, lockThread.i);
+ }
+}

0 comments on commit 49c2826

Please sign in to comment.