易截截图软件、单文件、免安装、纯绿色、仅160KB

JAVA and C++版信号量(PV操作)

import java.util.concurrent.Semaphore;
/**
* 抽象任务,具体的执行任务,归实现类负责
*
* @author Administrator
*
*/
public abstract class Task {
public abstract void run();
private Semaphore s;
private boolean hasExisted = false;
public void P(final Semaphore s) throws InterruptedException {
if (s == null) { // 申请空的信号量
throw new InterruptedException("不能为空");
}
if (hasExisted) {// 已经申请了一个资源,还没有释放
throw new InterruptedException("已经占用一个资源");
}
s.acquire();// 阻塞
this.s = s;
hasExisted = true;
}
public boolean V() {
if (!hasExisted) {
return false;// 没沾有资源就不能说释放了
}
s.release();//释放资源
hasExisted = false;
s = null;
return true;
}
}
import java.util.concurrent.Semaphore;
/**
* 用信号量实现互斥
*
* @author Administrator
*
*/
public class Mutex extends Semaphore {
private static final long serialVersionUID = 1L;
public Mutex() {
super(1);//互斥是1
}
} import java.util.concurrent.Semaphore;
public class Test {
public static void main(String[] args) {
// final Semaphore s = new Semaphore(2);//信号量,执行结果run the task1 run the
// task2 run the task3
final Semaphore s = new Mutex();// 互斥 run the task1 run the task2 run
// the task3
new Thread() {
public void run() {
Task1 task2 = new Task1();
try {
task2.P(s);// 申请资源
task2.run();// 执行任务
task2.V();// 释放资源
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
Task2 task2 = new Task2();
try {
task2.P(s);
task2.run();
task2.V();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
Task3 task2 = new Task3();
try {
task2.P(s);
task2.run();
task2.V();
} catch (InterruptedException e)


相关文档:

Java多线程编程详解


一、理解多线程
    多线程是这样一种机制,它允许在程序中并发执行多个指令流,每个指令流都称为一个线程,彼此间互相独立。线程又称为轻量级进程,它和进程一样拥有独立的执行控制,由操作系统负责调度,区别在于线程没有独立的存储空间,而是和所属进程中的其它线程共享一个存储空间,这使得线程间的 ......

JAVA 彩票程序

import java.io.*;
public class CaiPiao {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String str;
  BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in ......

java加密和数字签名2 私钥加密

近初步接触了下Java加密和数字签名的相关内容,我学习的过程大概分五步:
1)消息摘要
2)私钥加密
3)公钥加密
4)数字签名
5) 数字证书
下面的代码是第二部分:私钥加密
希望能为刚刚接触这个的朋友们省点事
package security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import ......

java加密和数字签名3 公钥加密

最近初步接触了下Java加密和数字签名的相关内容,我学习的过程大概分五步:
1)消息摘要
2)私钥加密
3)公钥加密
4)数字签名
5)数字证书
下面的代码是第三部分:公钥加密
希望能为刚刚接触这个的朋友们省点事
package security;
import java.security.KeyPair;
import java.security.KeyPairGenerator ......

java加密和数字签名5 数字证书

最近初步接触了下Java加密和数字签名的相关内容,我学习的过程大概分五步:
1)消息摘要
2)私钥加密
3)公钥加密
4)数字签名
5)数字证书
下面的代码是第五部分:数字证书
比起前四部分,这部分就稍微麻烦点了,我想我有必要给刚刚接触数字证书的朋友们,把在本地跑通下面代码的前提说一下:
1此例是对&l ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号