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