操作系统课上讲过,信号机制最开始是用无限循环实现的,信号量只是一个int型整数。
wait(S) {
while(s<=0) {
; // no-op
}
S--;
}
signal(S) {
S++;
}
后来,将信号定义为结构体,由value和进程两部分组成。
typedef struct {
int value;
struct process * L;
} semaphore;
void wait(semaphore S) {
S.value--;
if(S.value < 0) {
add this process to S.L;
block();
}
}
void signal(semaphore S) {
S.value++;
if(S.value <= 0) {
remove a process from S.L;
wakeup(P);
}
}
很多学Java的同学,一直苦恼于多线程编程的问题。因为,Java JDK里的确提供了很多现成的线程操作方法,但是真正运用总是会抛出异常……。其实,Java提供的wait 和 notify 方法对于我们构建自己的并发控制模块已经是绰绰有余了。认识两个方法有两点必须要注意的:一,这两个方法是Object类的方法,也就是说Java中任何一个类都可以充当锁得角色;二,这两个方法必须放大synchronized 代码块里,以确保其执行时不受Java 多线程机制的影响。跟C写的信号量类比的话,wait 和 notify 相当于 block 和 wakeup ,而 synchronized 则确保wait 与 signal 方法的原子性。下面来看示例代码:
import java.util.LinkedList;
import core.concurrent.LockManager;
import core.concurrent.LockState;
public class LockerTest {
private static LockerTest locker = null;
public static LockerTest getLocker() {
if (locker == null) {
locker = new LockerTest();
}
return locker;
}
private volatile int count = 1;
private volatile LinkedList<Thread> waiting = new LinkedList<Thread>();
public synchronized void wait(String name) {
count--;
System.out.println(name + " wait " + count);
if (count < 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void signal() {
count++;
System.out.println("signal " + count);
if (count < 1) {
notify();
}
}
public static void main(String[] args) {
new Client("name1").start();
new Client("name2").start();
new Client("name3").start();
}
}
class Client extends Thread {
private String name;
public Client (String name) {
this.name = name;
}
public void run() {
LockManager.getLockManager().lock("adsf", LockState.excusive);
new ClientFood().show(name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LockManager.getLockManager().unlock("adsf");
}
}
class ClientFood {
private static String name; // 这里的共享资源
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 这里需要并发控制的代码段
public void show(String newname) {
System.out.println("odd name = " + this.getName());
this.setName(newname);
for (int i = 0; i < 1000; i++) {
this.setName(newname + "_" + i);
}
System.out.println("new name = " + this.getName());
}
}
悠嘻,收工……