本文共 2504 字,大约阅读时间需要 8 分钟。
直接上代码,请各位看看,有兴趣的跑一下,求指教
package com.ginkgocap.ywxt.utils;
import java.util.HashMap;
import java.util.Map;
public class PetersonAlgorithm {
static class PetersonIdentity {
// flags 中的key是线程id,value是该线程是否请求了某个资源resource
public Mapflags;
// turn变量为了解决“饥饿”问题
public Long turn;
public PetersonIdentity() {
flags = new HashMap();
}
}
// metexes 中的key是 临界资源, value是 各线程对该资源的请求访问情况
public static Mapmutexes = new
HashMap();
public static void lock(Object resource) {
PetersonIdentity pi;
if (mutexes.get(resource) == null) {
pi = new PetersonIdentity();
} else {
pi = (PetersonIdentity) mutexes.get(resource);
}
Long currentThreadId = Thread.currentThread().getId();
// 当前线程请求访问resource
pi.flags.put(currentThreadId, Boolean.TRUE);
pi.turn = currentThreadId;
mutexes.put(resource, pi);
Boolean isQuested = true;
// 如果其他线程已经进入了临界区,则 该线程空转,浪费cpu
while (isQuested.equals(Boolean.TRUE)
&& pi.turn.equals(currentThreadId)) {
isQuested = false;
for (Map.Entrye : pi.flags.entrySet())
{
if (e.getKey() != currentThreadId
&& e.getValue().equals(Boolean.TRUE)) {
isQuested = true;
break;
}
}
// System.out.println("busy spin");
}
}
public static void release(Object object) {
PetersonIdentity pi;
pi = (PetersonIdentity) mutexes.get(object);
Long currentThreadId = Thread.currentThread().getId();
// 表示该线程已经用完了该临界资源
pi.flags.put(currentThreadId, Boolean.FALSE);
}
public static void main(String... strings) {
// 票
Ticket t = new Ticket();
// 印票机
Thread add = new Thread(new Add(t));
// 售票员
Thread del = new Thread(new Delete(t));
add.start();
del.start();
}
}
class Ticket {
public int count = 0;
}
class Add implements Runnable {
public Ticket tickets;
public Add(Ticket t) {
tickets = t;
}
@Override
public void run() {
// 票作为一种临界资源,在印票的时候,售票员不能卖
PetersonAlgorithm.lock(tickets);
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tickets.count++;
System.out.println(tickets.count);
}
// 退出对临界资源的访问,售票员可以卖了
PetersonAlgorithm.release(tickets);
}
}
class Delete implements Runnable {
public Ticket tickets;
public Delete(Ticket t) {
tickets = t;
}
@Override
public void run() {
// TODO Auto-generated method stub
PetersonAlgorithm.lock(tickets);
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tickets.count--;
System.out.println(tickets.count);
}
PetersonAlgorithm.release(tickets);
}
}
转载地址:http://sodnv.baihongyu.com/