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

王朝java/jsp·作者佚名  2006-01-31
窄屏简体版  字體: |||超大  

[问题描述]

希望所有相同名字的现成互斥执行,即分组并发,如下例:

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);

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航