遇到一个线程方法体生命周期的问题,虽然开始用Thread 的原生类可以很好的解决着个问题,但是总觉的应该用相关的锁可以解决这总问题, 问题如下:
我门用运行一个方法时,有可能需要线程来做这件事情,但是却不知道他们什么时候运行完毕,用Thread.sleep()可以阻塞住,但是这样效率会限制在Thread sleep的interval 内,而且有可能死循环,代码如下:
/**
*
* @author zx04741
*/
public class test {
//private static Semaphore sem = new Semaphore(1);
public static void test1() {
try {
MyThread t = new MyThread();
t.start();
while (!t.over) {
Thread.sleep(100);
}
MyThread t1 = new MyThread();
t1.start();
while (!t1.over) {
Thread.sleep(100);
}
} catch (InterruptedException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
}
static class MyThread extends Thread {
private static int GO = 0;
public volatile static boolean over=false;
public void run() {
try {
//sem.acquire();
over=false;
System.out.println(Thread.currentThread().getId() + ",val:" + (++GO));
Thread.sleep(3000);
over=true;
//sem.release();
} catch (InterruptedException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) {
test1();
}
}
信号量的的解释:
一个计数信号量。从概念上讲,信号量维护了一个许可集合。如有必要,在许可可用前会阻塞每一个 acquire()
,然后再获取该许可。每个 release()
添加一个许可,从而可能释放一个正在阻塞的获取者。但是,不使用实际的许可对象,Semaphore 只对可用许可的号码进行计数,并采取相应的行动。
Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目。
获得一项前,每个线程必须从信号量获取许可,从而保证可以使用该项。该线程结束后,将项返回到池中并将许可返回到该信号量,从而允许其他线程获取该项。注意,调用 acquire()
时无法保持同步锁定,因为这会阻止将项返回到池中。信号量封装所需的同步,以限制对池的访问,这同维持该池本身一致性所需的同步是分开的。
我们在这里只要一个限制访问就可以了,代码改后如下:
/**
*
* @author zx04741
*/
public class test {
private static Semaphore sem = new Semaphore(1);
public static void test1() {
MyThread t = new MyThread();
t.start();
MyThread t1 = new MyThread();
t1.start();
}
static class MyThread extends Thread {
private static int GO = 0;
public void run() {
try {
sem.acquire();
System.out.println(Thread.currentThread().getId() + ",val:" + (++GO));
Thread.sleep(3000);
sem.release();
} catch (InterruptedException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) {
test1();
}
其实信号量会用在我门的一些IDE里面,我们在调试程序的时候设置断点应该就这种锁机制, 和MFC 里面的CSemaphore应该是一样的底层, 应该是属于互斥MUTEX的...