文章来源:http://blog.sina.com.cn/s/blog_6560efc9010185fc.html
接近一周没更新《Java线程》专栏了,主要是这周工作上比较忙,生活上也比较忙,呵呵,进入正题,上一篇讲述了并发包下的Lock,Lock可以更好的解决线程同步问题,使之更面向对象,并且ReadWriteLock在处理同步时更强大,那么同样,线程间仅仅互斥是不够的,还需要通信,本篇的内容是基于上篇之上,使用Lock如何处理线程通信。
- public
class ThreadTest2 { -
public static void main(String[] args) { -
final Business business = new Business(); -
new Thread(new Runnable() { -
@Override -
public void run() { -
threadExecute(business, "sub"); -
} -
}).start(); -
threadExecute(business, "main"); -
} -
public static void threadExecute(Business business, String threadType) { -
for(int i = 0; i < 100; i++) { -
try { -
if("main".equals(threadType)) { -
business.main(i); -
} else { -
business.sub(i); -
} -
} catch (InterruptedException e) { -
e.printStackTrace(); -
} -
} -
} - }
- class
Business { -
private boolean bool = true; -
private Lock lock = new ReentrantLock(); -
private Condition condition = lock.newCondition(); -
public void main(int loop) throws InterruptedException { -
lock.lock(); -
try { -
while(bool) { -
condition.await();//this.wait(); -
} -
for(int i = 0; i < 100; i++) { -
System.out.println("main thread seq of " + i + ", loop of " + loop); -
} -
bool = true; -
condition.signal();//this.notify(); -
} finally { -
lock.unlock(); -
} -
} -
public void sub(int loop) throws InterruptedException { -
lock.lock(); -
try { -
while(!bool) { -
condition.await();//this.wait(); -
} -
for(int i = 0; i < 10; i++) { -
System.out.println("sub thread seq of " + i + ", loop of " + loop); -
} -
bool = false; -
condition.signal();//this.notify(); -
} finally { -
lock.unlock(); -
} -
} - }
- class
BoundedBuffer { -
final Lock lock = new ReentrantLock();//锁对象 -
final Condition notFull = lock.newCondition();//写线程条件 -
final Condition notEmpty = lock.newCondition();//读线程条件 -
-
final Object[] items = new Object[100];//缓存队列 -
int putptr, takeptr, count; -
-
public void put(Object x) throws InterruptedException { -
lock.lock(); -
try { -
while (count == items.length)//如果队列满了 -
notFull.await();//阻塞写线程 -
items[putptr] = x;//赋值 -
if (++putptr == items.length) putptr = 0;//如果写索引写到队列的最后一个位置了,那么置为0 -
++count;//个数++ -
notEmpty.signal();//唤醒读线程 -
} finally { -
lock.unlock(); -
} -
} -
-
public Object take() throws InterruptedException { -
lock.lock(); -
try { -
while (count == 0)//如果队列为空 -
notEmpty.await();//阻塞读线程 -
Object x = items[takeptr];//取值 -
if (++takeptr == items.length) takeptr = 0;//如果读索引读到队列的最后一个位置了,那么置为0 -
--count;//个数-- -
notFull.signal();//唤醒写线程 -
return x; -
} finally { -
lock.unlock(); -
} -
} -
}