RSS
热门关键字:  java  Ajax  JSP  JSF  Struts
当前位置 : 首页>Java>列表

Java语言深入-对JAVA 的多线程浅析

来源: 作者: 时间:2008-03-03 点击:

sem.writeLock();

System.out.println("Write op:"+getName());

try {sleep((int)(Math.random()*50));}

catch(InterruptedException e){;}

System.out.println("Unlocking writeLock:"+getName());

sem.writeUnlock();

}

}

}

public class testSem{

public static void main(String argv[]){

Semaphore lock = new Semaphore();

new Process("1","read",lock);

new Process("2","read",lock);

new Process("3","write",lock);

new Process("4","read",lock);

}

}

testSem 类从process类的四个实例开始,它是个线程,用来读或写一个共享文

件。Semaphore类保证访问不会破坏文件,执行程序,输出结果如下:

Trying to get readLock:1

Read op:1

Trying to get readLock:2

Read op:2

Trying to get writeLock:3

Trying to get readLock:4

Read op:4

Unlocking readLock:1

Unlocking readLock:2

Unlocking readLock:4

Write op:3

Unlocking writeLock:3

最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册