国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java Javagetting Started what is java thread synchronization

what is java thread synchronization

Dec 09, 2019 pm 04:27 PM
java Thread synchronization

what is java thread synchronization

#Thread synchronization

When calling the same object between multiple threads, for the safety and accuracy of operation, the object needs to be synchronized to ensure that the result of the object is correct when used by each thread, and the status of the object is Reasonably, this part involves knowledge points such as synchronization and thread locks. This part only involves the concepts of synchronized and synchronization lock (Lock).

synchronized

The synchronized keyword can modify objects and methods. The usual usage is as follows:

//同步代碼塊
synchronized(Object object){
...
}
//或者
//同步方法
public synchronized void test(){
...
}

There is a concept of synchronization monitor, such as the above The object object of the synchronized code block and the this object of the synchronized method will be monitored synchronously. When multiple threads call a synchronized code block or method at the same time, only one thread can obtain the synchronously monitored object lock at any time. After executing the code The lock will not be released until later. During this period, other calling threads can only wait for the lock to be released before calling.

The sell method in the SellRunnable class mentioned above also uses synchronized. The code above executes too fast, so it cannot be sensed. If you modify it, you can understand the difference between synchronized and not.

public class ThreadTest {
    public static void main(String[] args) {
        SellRunnable sellRunnable = new SellRunnable();
        Thread thread1 = new Thread(sellRunnable, "1");
        Thread thread2 = new Thread(sellRunnable, "2");
        Thread thread3 = new Thread(sellRunnable, "3");
        thread2.start();
        thread1.start();
        thread3.start();
    }
}
class SellRunnable implements Runnable {
    //有十張票
    int index = 10;
    public void sell() {
        if (index >= 1) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            index--;
            System.out.println("售貨窗口:" + Thread.currentThread().getName() + 
            " 賣出了一張票,剩余:
            " + index);
        } else {
            System.out.println("售貨窗口:" + Thread.currentThread().getName() + " 買票時沒票了");
        }
    }
    @Override
    public void run() {
        while (index > 0) {
            System.out.println("售貨窗口:" + Thread.currentThread().getName() + " 開始買票");
            sell();
        }
    }
}
//執(zhí)行結(jié)果:
售貨窗口:1 開始買票
售貨窗口:2 開始買票
售貨窗口:3 開始買票
售貨窗口:2  賣出了一張票,剩余:9
售貨窗口:2 開始買票
售貨窗口:1  賣出了一張票,剩余:9
售貨窗口:1 開始買票
售貨窗口:3  賣出了一張票,剩余:8
售貨窗口:3 開始買票
售貨窗口:1  賣出了一張票,剩余:6
售貨窗口:1 開始買票
售貨窗口:2  賣出了一張票,剩余:6
售貨窗口:2 開始買票
售貨窗口:3  賣出了一張票,剩余:5
售貨窗口:3 開始買票
售貨窗口:1  賣出了一張票,剩余:4
售貨窗口:1 開始買票
售貨窗口:2  賣出了一張票,剩余:3
售貨窗口:3  賣出了一張票,剩余:2
售貨窗口:3 開始買票
售貨窗口:2 開始買票
售貨窗口:3  賣出了一張票,剩余:1
售貨窗口:2  賣出了一張票,剩余:0
售貨窗口:1  賣出了一張票,剩余:1
Process finished with exit code 0  //可以看到,票數(shù)減少是錯誤的
//sell方法添加synchronized修飾符后 執(zhí)行結(jié)果:
public synchronized void sell() {
        if (index >= 1) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            index--;
            System.out.println("售貨窗口:" + Thread.currentThread().getName() + 
            " 賣出了一張票,剩余:
            " + index);
        } else {
            System.out.println("售貨窗口:" + Thread.currentThread().getName() + " 買票時沒票了");
        }
    }
售貨窗口:2 開始買票
售貨窗口:3 開始買票
售貨窗口:1 開始買票
售貨窗口:2  賣出了一張票,剩余:9
售貨窗口:2 開始買票
售貨窗口:1  賣出了一張票,剩余:8
售貨窗口:1 開始買票
售貨窗口:3  賣出了一張票,剩余:7
售貨窗口:3 開始買票
售貨窗口:1  賣出了一張票,剩余:6
售貨窗口:1 開始買票
售貨窗口:2  賣出了一張票,剩余:5
售貨窗口:2 開始買票
售貨窗口:1  賣出了一張票,剩余:4
售貨窗口:1 開始買票
售貨窗口:1  賣出了一張票,剩余:3
售貨窗口:1 開始買票
售貨窗口:3  賣出了一張票,剩余:2
售貨窗口:3 開始買票
售貨窗口:1  賣出了一張票,剩余:1
售貨窗口:1 開始買票
售貨窗口:1  賣出了一張票,剩余:0
售貨窗口:2 買票時沒票了
售貨窗口:3 買票時沒票了
Process finished with exit code 0  // 可以看到,票數(shù)是正常減少的

After the above synchronization of the sell method, at a certain moment, only one thread will call this method, so the result obtained when judging the index is the correct result.

During the above synchronization, thread safety is ensured by reducing operating efficiency. For this reason, do not synchronize the unnecessary methods and objects in the thread class, and only synchronize the resources or objects with competition. The code is synchronized.

After synchronization identification, the following points can release the lock:

Code block, method execution is completed (normal completion, return or break, exception thrown)

Call The wait method is used to pause the current thread.

When a thread executes a synchronized code block, the sleep and yield methods will not release the synchronization lock, nor will the suspend method (try to avoid using suspend and resume to manipulate the thread state during thread operation, which is easy Leading to deadlock.)

Synchronized Lock

The synchronized mentioned above is a keyword in java, and it is also mentioned in When sleeping or performing IO operations, the thread will not release the thread lock, and other threads need to wait. This sometimes reduces the execution efficiency, so an alternative that can release the thread lock when the thread is blocked is needed. Lock It appeared just to solve this problem.

Lock is a class in java, in the java.util.concurrent.locks package, the specific code is as follows:

public interface Lock {
    void lock();//加鎖
    void lockInterruptibly() throws InterruptedException;//加鎖
    boolean tryLock();//加鎖
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;//加鎖
    void unlock();//釋放鎖
    Condition newCondition();//線程協(xié)作中用到
}

An implementation subclass of the Lock interface is ReentrantLock, in java. Under the util.concurrent.locks package, the source code of ReentrantLock is as follows:

public class ReentrantLock implements Lock, Serializable {
    private static final long serialVersionUID = 7373984872572414699L;
    private final ReentrantLock.Sync sync;
    public ReentrantLock() {
        this.sync = new ReentrantLock.NonfairSync();
    }
    public ReentrantLock(boolean var1) {//是否創(chuàng)建公平鎖
        this.sync = (ReentrantLock.Sync)(var1?new ReentrantLock.FairSync():new  ReentrantLock.
        NonfairSync());
    }
    public void lock() {
        this.sync.lock();
    }
    public void lockInterruptibly() throws InterruptedException {
        this.sync.acquireInterruptibly(1);
    }
    public boolean tryLock() {
        return this.sync.nonfairTryAcquire(1);
    }
    public boolean tryLock(long var1, TimeUnit var3) throws InterruptedException {
        return this.sync.tryAcquireNanos(1, var3.toNanos(var1));
    }
    public void unlock() {
        this.sync.release(1);
    }
    public Condition newCondition() {
        return this.sync.newCondition();
    }
    public int getHoldCount() {//當前線程持有該鎖的數(shù)量
        return this.sync.getHoldCount();
    }
    public boolean isHeldByCurrentThread() {//該鎖是否被當前線程持有
        return this.sync.isHeldExclusively();
    }
    public boolean isLocked() {//是否被其他線程持有該鎖
        return this.sync.isLocked();
    }
    public final boolean isFair() {//是否是公平鎖
        return this.sync instanceof ReentrantLock.FairSync;
    }
    protected Thread getOwner() {//當前鎖的持有線程
        return this.sync.getOwner();
    }
    public final boolean hasQueuedThreads() {//是否有線程在等待該鎖
        return this.sync.hasQueuedThreads();
    }
    public final boolean hasQueuedThread(Thread var1) {//目標線程是否在等待該鎖
        return this.sync.isQueued(var1);
    }
    public final int getQueueLength() {//等待該鎖線程的數(shù)量
        return this.sync.getQueueLength();
    }
    protected Collection<Thread> getQueuedThreads() {//獲取所有等待該鎖的線程集合
        return this.sync.getQueuedThreads();
    }
    ...
    
}

How to use Lock

lock

lock() is used to acquire the lock. If the lock is occupied by other threads, it will wait.

public class LockTest {
    public static void main(String[] args) {
        com.test.java.SellRunnable sellRunnable = new com.test.java.SellRunnable();
        Thread thread1 = new Thread(sellRunnable, "1號窗口");
        Thread thread2 = new Thread(sellRunnable, "2號窗口");
        Thread thread3 = new Thread(sellRunnable, "3號窗口");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
public class SellRunnable implements Runnable {
    //有十張票
    int index = 10;
    Lock lock = new ReentrantLock();
    public void sell() {
        try {
            lock.lock();
            System.out.println("售貨柜臺:" + Thread.currentThread().getName() + 
            "獲取了票源+++++");
            if (index >= 1) {
                index--;
                System.out.println("售貨柜臺:" + Thread.currentThread().getName() + 
                "賣出了一張票,剩余:
                " + index);
            } else {
                System.out.println("售貨柜臺:" + Thread.currentThread().getName() + 
                "買票時沒票了000");
            }
        } finally {
            lock.unlock();
        }
    }
    @Override
    public void run() {
        while (index > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sell();
        }
    }
}

Run result:

售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:9
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:8
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:7
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:6
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:5
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:4
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:3
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:2
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:1
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:0
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口買票時沒票了000
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口買票時沒票了000
Process finished with exit code 0  //每一個窗口都隨機獲取票源、然后賣出票

tryLock

tryLock() tries to acquire the lock. If the acquisition is successful, it returns true. If it fails, it returns false and will not enter the waiting state.

public class SellRunnable implements Runnable {
    //有十張票
    int index = 10;
    Lock lock = new ReentrantLock();
    public void sell() {
        if (lock.tryLock()) {
            try {
                System.out.println("售貨柜臺:" + Thread.currentThread().getName() + 
                "獲取了票源+++++");
                if (index >= 1) {
                    index--;
                    System.out.println("售貨柜臺:" + Thread.currentThread().getName() + 
                    "賣出了一張票,剩余:" + index);
                } else {
                    System.out.println("售貨柜臺:" + Thread.currentThread().getName() + 
                    "買票時沒票了000");
                }
            } finally {
                lock.unlock();
            }
        } else {
           System.out.println("售貨柜臺:" + Thread.currentThread().getName()+"沒有獲取票源?。?!");
        }
    }
    @Override
    public void run() {
        while (index > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sell();
        }
    }
}

Running result:

售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:3號窗口沒有獲取票源?。?!
售貨柜臺:2號窗口沒有獲取票源!?。?售貨柜臺:1號窗口賣出了一張票,剩余:9
售貨柜臺:2號窗口沒有獲取票源?。?!
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:8
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:7
售貨柜臺:1號窗口沒有獲取票源?。?!
售貨柜臺:3號窗口沒有獲取票源?。。?售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:6
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:2號窗口沒有獲取票源?。?!
售貨柜臺:3號窗口沒有獲取票源!?。?售貨柜臺:1號窗口賣出了一張票,剩余:5
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:1號窗口沒有獲取票源?。。?售貨柜臺:2號窗口賣出了一張票,剩余:4
售貨柜臺:3號窗口沒有獲取票源?。?!
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:2號窗口沒有獲取票源?。?!
售貨柜臺:3號窗口沒有獲取票源?。?!
售貨柜臺:1號窗口賣出了一張票,剩余:3
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:2
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:3號窗口沒有獲取票源?。?!
售貨柜臺:2號窗口賣出了一張票,剩余:1
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:0
售貨柜臺:3號窗口沒有獲取票源?。?!
售貨柜臺:2號窗口沒有獲取票源?。?!
Process finished with exit code 0//沒有獲取到貨源的票口,就直接沒有等待,進入下次買票

tryLock(long time, TimeUnit unit)

tryLock(long time, TimeUnit unit) can be set to wait for a period of time when the lock cannot be obtained. . //The first parameter is always long, the second parameter time unit

public class SellRunnable implements Runnable {
    //有十張票
    int index = 10;
    Lock lock = new ReentrantLock();
    public void sell() {
        try {
            if (lock.tryLock(1000, TimeUnit.MILLISECONDS)) {
                try {
                    System.out.println("售貨柜臺:" + Thread.currentThread().getName() + 
                    "獲取了票源+++++");
                    if (index >= 1) {
                        index--;
                        System.out.println("售貨柜臺:" + Thread.currentThread().getName()
                         +"賣出了一張票,剩余:" + index);
                    } else {
                        System.out.println("售貨柜臺:" + Thread.currentThread().
                        getName()  + "買票時沒票了000");
                    }
                    try {
                        Thread.sleep(2000);//人為加入買票時間
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println("售貨柜臺:" + Thread.currentThread().getName() + 
                "沒有獲取票源?。?!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while (index > 0) {
            try {
                Thread.sleep(500);//要不執(zhí)行太快,看不出效果
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sell();
        }
    }
}

Execution result:

售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:9
售貨柜臺:2號窗口沒有獲取票源?。?!
售貨柜臺:3號窗口沒有獲取票源?。?!
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:8
售貨柜臺:3號窗口沒有獲取票源?。。?售貨柜臺:1號窗口沒有獲取票源?。?!
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:7
售貨柜臺:1號窗口沒有獲取票源?。?!
售貨柜臺:2號窗口沒有獲取票源!??!
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:6
售貨柜臺:2號窗口沒有獲取票源!??!
售貨柜臺:3號窗口沒有獲取票源?。?!
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:5
售貨柜臺:3號窗口沒有獲取票源?。。?售貨柜臺:1號窗口沒有獲取票源?。?!
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:4
售貨柜臺:1號窗口沒有獲取票源?。?!
售貨柜臺:2號窗口沒有獲取票源?。?!
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:3
售貨柜臺:2號窗口沒有獲取票源?。?!
售貨柜臺:3號窗口沒有獲取票源?。。?售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:2
售貨柜臺:3號窗口沒有獲取票源?。。?售貨柜臺:1號窗口沒有獲取票源?。?!
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:1
售貨柜臺:1號窗口沒有獲取票源!?。?售貨柜臺:2號窗口沒有獲取票源?。?!
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:0
售貨柜臺:2號窗口沒有獲取票源!??!
售貨柜臺:3號窗口沒有獲取票源!??!
Process finished with exit code 0 //當買票時間大約等待時間時,則沒有獲取票源的窗口不買票,進入下個買票機會

Shorten the ticket purchase time:

try {
    Thread.sleep(500);//人為加入買票時間
} catch (InterruptedException e) {
    e.printStackTrace();
}

Execution result:

售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:9
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:8
售貨柜臺:3號窗口沒有獲取票源?。?!
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:7
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:6
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:5
售貨柜臺:3號窗口沒有獲取票源!??!
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:4
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:3
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:2
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:1
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:0
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口買票時沒票了000
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口買票時沒票了000
Process finished with exit code 0 //等待時間內(nèi)獲取到票源了,也就賣出票了

lockInterruptibly

lockInterruptibly() When acquiring a lock through this method, if the lock is being held by another thread, it will enter the waiting state, but this waiting process can be interrupted by calling Thread The object's interrupt method can interrupt waiting. When interrupted, an InterruptedException is thrown, which needs to be caught or declared to be thrown.

public class ThreadTest {
    public static void main(String[] args) {
        SellRunnable sellRunnable = new SellRunnable();
        Thread thread1 = new Thread(sellRunnable, "1號窗口");
        Thread thread2 = new Thread(sellRunnable, "2號窗口");
        Thread thread3 = new Thread(sellRunnable, "3號窗口");
        thread1.start();
        try {
            Thread.sleep(500);//確保窗口1號先獲取鎖
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.start();
        thread3.start();
        try {
            Thread.sleep(2000);//等待兩秒后,打斷窗口2、3的等待
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.interrupt();
        thread3.interrupt();
    }
}
SellRunnable中等待時間加長:
try {
    Thread.sleep(5000);//人為加入買票時間
} catch (InterruptedException e) {
    e.printStackTrace();
}

Execution results:

售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:9
售貨柜臺:3號窗口被打斷了      //這個地方被打斷了
售貨柜臺:2號窗口被打斷了      //這個地方被打斷了
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:8
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:7
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:6
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:5
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:4
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:3
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口賣出了一張票,剩余:2
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口賣出了一張票,剩余:1
售貨柜臺:1號窗口獲取了票源+++++
售貨柜臺:1號窗口賣出了一張票,剩余:0
售貨柜臺:2號窗口獲取了票源+++++
售貨柜臺:2號窗口買票時沒票了000
售貨柜臺:3號窗口獲取了票源+++++
售貨柜臺:3號窗口買票時沒票了000
Process finished with exit code 0

Comparison between synchronized and Lock

Through the above code, you can see the difference between Lock and synchronized Several connections and differences:

Both are reentrant locks

Reentrant lock means that after a thread acquires the object lock, the thread can acquire the object lock again without Not blocked. For example, after multiple methods (or a method called recursively) in the same class are synchronized or locked, the same thread can acquire the object's lock without being blocked when calling these two methods.

Example of non-reentrant lock:

public class Lock{
    private boolean isLocked = false;
    public void lock(){
        while(isLocked){    
            wait();
        }
        isLocked = true;
    }
    public void unlock(){
        isLocked = false;
        notify();
    }
}
//使用方法:
public class Test{
    Lock lock = new Lock();
    public void test1(){
        lock.lock();
        test2();
        lock.unlock();
    }
    public void test2(){
        lock.lock();
        ...
        lock.unlock();
    }
}

When the Test class calls the test1 method and calls test2 after executing lock.lock(), it will wait forever and become dead. Lock.

Reentrant lock design principle:

public class Lock{
    private boolean isLocked = false;
    private Thread lockedThread = null;
    int lockedCount = 0;
    public void lock(){
        Thread thread = Thread.currentThread();
        while(isLocked && thread != lockedThread){    
            wait();
        }
        isLocked = true;
        lockedCount++;
        lockedThread = thread;
    }
    public void unlock(){
        Thread thread = Thread.currentThread();
        if(thread == lockedThread){    
            lockedCount--;
            if(lockedCount == 0){
                isLocked = false;
                lockedThread = null;
                notify();
            }
        }
    }
}

After calling the test1 method of the Test class, the test2 method can also be executed smoothly.

In terms of implementation, synchronized basically uses counters to achieve reentrancy.

Lock is an interruptible lock, synchronized cannot be interrupted.

當一個線程B執(zhí)行被鎖的對象的代碼時,發(fā)現(xiàn)線程A已經(jīng)持有該鎖,那么線程B就會進入等待,但是synchronized就無法中斷該等待過程,而Lock就可以通過lockInterruptibly方法拋出異常從而中斷等待,去處理別的事情。

Lock可創(chuàng)建公平鎖,synchronized是非公平鎖。

公平鎖的意思是按照請求的順序來獲取鎖,不平公鎖就無法保證線程獲取鎖的先后次序。

Lock可以知道是否獲取到鎖,synchronized不可以。

synchronized在發(fā)生異?;蛘哌\行完畢,會自動釋放線程占有的鎖。而Lock需要主動釋放鎖,否則會鎖死;

synchronized在阻塞時,別的線程無法獲取鎖,Lock可以(這也是lock設計的一個目的)。

讀寫鎖

多個線程對同一個文件進行寫操作時,會發(fā)生沖突所以需要加鎖,但是對同一個文件進行讀操作的時候,使用上面的方法會造成效率的降低,所以基于這種情況,產(chǎn)生了ReadWriteLock這個接口:

public interface ReadWriteLock {
    /**
     * Returns the lock used for reading.
     *
     * @return the lock used for reading.
     */
    Lock readLock();//讀的鎖
 
    /**
     * Returns the lock used for writing.
     *
     * @return the lock used for writing.
     */
    Lock writeLock();//寫的鎖
}

這個接口的實現(xiàn)類是ReentrantReadWriteLock,其源代碼如下:

public class ReentrantReadWriteLock implements ReadWriteLock, Serializable {
    private static final long serialVersionUID = -6992448646407690164L;
    private final ReentrantReadWriteLock.ReadLock readerLock;
    private final ReentrantReadWriteLock.WriteLock writerLock;
    ...
    public ReentrantReadWriteLock.WriteLock writeLock() {//獲取write lock
        return this.writerLock;
    }
    public ReentrantReadWriteLock.ReadLock readLock() {//獲取read lock
        return this.readerLock;
    }
    ...
}

使用方法和Lock一樣,使用到write時調(diào)用writeLock()方法獲取lock進行加鎖,使用到read時調(diào)用readLock()方法進行加鎖,需要注意的知識點如下:

線程A占用寫鎖,線程B在申請寫、讀的時候需要等待。

線程A占用讀鎖,線程B在申請寫操作時,需要等待。

線程A占用讀鎖,線程B獲取讀操作時可以獲取到。

總結(jié)

如果需要效率提升,則建議使用Lock,如果效率要求不高,則synchronized滿足使用條件,業(yè)務邏輯寫起來也簡單,不需要手動釋放鎖。

PHP中文網(wǎng),有大量免費的JAVA入門教程,歡迎大家學習!

The above is the detailed content of what is java thread synchronization. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to iterate over a Map in Java? How to iterate over a Map in Java? Jul 13, 2025 am 02:54 AM

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)-&gt

Java Optional example Java Optional example Jul 12, 2025 am 02:55 AM

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

How to fix java.io.NotSerializableException? How to fix java.io.NotSerializableException? Jul 12, 2025 am 03:07 AM

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

Comparable vs Comparator in Java Comparable vs Comparator in Java Jul 13, 2025 am 02:31 AM

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

Java method references explained Java method references explained Jul 12, 2025 am 02:59 AM

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

How to handle character encoding issues in Java? How to handle character encoding issues in Java? Jul 13, 2025 am 02:46 AM

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

How to parse JSON in Java? How to parse JSON in Java? Jul 11, 2025 am 02:18 AM

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.

Outlook shortcut for new email Outlook shortcut for new email Jul 11, 2025 am 03:25 AM

How to quickly create new emails in Outlook is as follows: 1. The desktop version uses the shortcut key Ctrl Shift M to directly pop up a new email window; 2. The web version can create new emails in one-click by creating a bookmark containing JavaScript (such as javascript:document.querySelector("divrole='button'").click()); 3. Use browser plug-ins (such as Vimium, CrxMouseGestures) to trigger the "New Mail" button; 4. Windows users can also select "New Mail" by right-clicking the Outlook icon of the taskbar

See all articles