用多例模式实现线程的分组并发执行

2008-02-23 09:32:47来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

[问题描述]
希望所有相同名字的现成互斥执行,即分组并发,如下例:
Thread threada1 = new thread(“1“);
Thread threada2 = new thread(“1“);
Thread threada3 = new thread(“1“);
Thread threadb1 = new thread(“2“);
Thread threaDB2 = new thread(“2“);
Thread threadb3 = new thread(“2”);
执行顺序(并不严格要求,只要同名的线程互斥执行):
threada1 申请锁
threada1 运行中
threadb1 申请锁
threadb1 运行中
threada2 申请锁
threada1 释放锁
threada2 运行中
threadb1 释放锁
threada2 释放锁
........

[代码]

package com.cozmic.Thread;
import Java.util.*;

public class MultiThreadInSameGroupExclusiveRunning {
public static void main(String[] args) {
MultiThreadInSameGroupExclusiveRunning untitled1 =
new MultiThreadInSameGroupExclusiveRunning();
untitled1.go();
}

/* * 生成不同组成员*/
public void go() {
for (int i = 0; i < 10; i ) {
new RunThread(“1“).start();
new RunThread(“1“).start();
new RunThread(“2“).start();
}
}
}

class RunThread extends Thread {
LockClass lockClass;
String str;
RunThread(String str) {
lockClass = LockClass.getLock(str); //获得锁,每个线程组共享一个
this.str = str;
}

public void run() {
System.out.println(“申请锁 ” this.getName() “ “ str);
lockClass.lock();
System.out.println(“执行中” this.getName() “ “ str);
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
System.out.println(ex);
} finally {
lockClass.unlock();
}

}
}

class LockClass {
private static HashMap hm = new HashMap();
private String str;
private LockClass(String str) {
this.str = str;
}

//多例模式
public synchronized static LockClass getLock(String str) {
LockClass lc = (LockClass) hm.get(str);
if (lc == null) {
lc = new LockClass(str);
hm.put(str, lc);
}

return lc;
}

private boolean isUsed = false;

public synchronized void lock() {
if (isUsed) {
try {
wait();
} catch (InterruptedException ex) {
System.out.println(ex);
}

}
isUsed = true;
}

public synchronized void unlock() {
isUsed = false;
notify();
System.out.println(“释放完了 ” hashCode() “ ” str);
}

}

上一篇: 我的一个读写oracle大字段的类(源码)
下一篇: java.io.FilenameFilter翻译

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:JNI初探二(windows平台开发)

下一篇:在J2ME中实现欢迎界面(附源代码)