[问题描述]
希望所有相同名字的现成互斥执行,即分组并发,如下例:
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);
}
}