Java互斥锁简单实例
本文实例讲述了Java互斥锁。分享给大家供大家参考。具体分析如下:
互斥锁,常常用于多个线程访问独占式资源,比如多个线程同时写一个文件,虽然互斥访问方式不够高效,但是对于一些应用场景却很有意义
//没有互斥锁的情况(可以自己跑跑看运行结果):
publicclassLockDemo{
//privatestaticObjectlock=newObject();
//static确保只有一把锁
privateinti=0;
publicvoidincreaseI(){
//synchronized(lock){
for(intk=0;k<10;k++){//对i执行10次增1操作
i++;
}
System.out.println(Thread.currentThread().getName()+"线程,i现在的值:"+i);
//}
}
publicstaticvoidmain(String[]args){
LockDemold=newLockDemo();
intthreadNum=1000;
//选择1000个线程让结果更加容易观测到
MyThread[]threads=newMyThread[threadNum];
for(inti=0;i<threads.length;i++){
threads[i]=newMyThread(ld);
//所有线程共用一个LockDemo对象
threads[i].start();
}
}
}
classMyThreadextendsThread{
LockDemold;
publicMyThread(LockDemold){
this.ld=ld;
}
publicvoidrun(){
ld.increaseI();
}
}
//加上互斥锁以后:
publicclassLockDemo{
privatestaticObjectlock=newObject();
//static确保只有一把锁
privateinti=0;
publicvoidincreaseI(){
synchronized(lock){
for(intk=0;k<10;k++){
//对i执行10次增1操作
i++;
}
System.out.println(Thread.currentThread().getName()+"线程,i现在的值:"+i);
}
}
publicstaticvoidmain(String[]args){
LockDemold=newLockDemo();
intthreadNum=1000;
//选择1000个线程让结果更加容易观测到
MyThread[]threads=newMyThread[threadNum];
for(inti=0;i<threads.length;i++){
threads[i]=newMyThread(ld);
//所有线程共用一个LockDemo对象
threads[i].start();
}
}
}
classMyThreadextendsThread{
LockDemold;
publicMyThread(LockDemold){
this.ld=ld;
}
publicvoidrun(){
ld.increaseI();
}
}
希望本文所述对大家的java程序设计有所帮助。