Java互斥鎖簡略實例。本站提示廣大學習愛好者:(Java互斥鎖簡略實例)文章只能為提供參考,不一定能成為您想要的結果。以下是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[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(); } }
願望本文所述對年夜家的java法式設計有所贊助。