Home > Java > javaTutorial > body text

Simple example of Java mutex lock

高洛峰
Release: 2017-01-23 13:14:31
Original
1908 people have browsed it

The examples in this article describe Java mutex locks. Share it with everyone for your reference. The specific analysis is as follows:

Mutex locks are often used for multiple threads to access exclusive resources, such as multiple threads writing a file at the same time. Although the mutual exclusion access method is not efficient enough, it is very useful for some application scenarios. Meaning

//没有互斥锁的情况(可以自己跑跑看运行结果):
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.length;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.length;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();
  }
}
Copy after login

I hope this article will be helpful to everyone’s Java programming

For more articles related to simple examples of Java mutex locks, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template