1. Principle
Lock synchronization lock
Signal() and await() of condition
2. Code examples
package com.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TasksTestLock extends Thread {
private static Lock lock = new ReentrantLock();
private static Condition condition = lock.newCondition();
private static int num = 1;
private int id;
public TasksTestLock(int id) {
this.id = id;
}
@Override
public void run() {
while (num <= 12) {
lock.lock();
System.out.println("Thread" + id + " num:" + num);
num++;
condition.signal();
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}
}
public static void main(String[] args) {
Thread thread0 = new TasksTestLock(0);
Thread thread1 = new TasksTestLock(1);
ExecutorService exec = Executors.newFixedThreadPool(3);
exec.submit(thread0);
exec.submit(thread1);
exec.shutdown();
}
}
3. Output results
Read More:
- Implementation of multithread sequential alternate execution by using lock in Java
- Global lock, table lock and row lock in MySQL
- Realize the simplest recursive call, simulate exception in thread “main” java.lang.stackoverflowerror exception
- Unity Cursor Lock& Camera Lock
- Python parallel processing makes full use of CPU to realize acceleration
- When linux installs rpm, it prompts: can’t create transaction lock on /var/lib/rpm/.rpm.lock error
- How to realize automatic assembly in springboot
- Learn English together | three ways to realize digital factorial with JavaScript
- Pytorch — nn.Sequential () module
- Using xrdp to realize windows remote desktop Ubuntu Linux
- Package pdftex.def Error: PDF mode expected, but DVI mode detected!_ mdpi_ Templatex compilation error in winedt
- DB2 encountered the problem of sqlcode = 911 lock table when updating record update
- Lock mechanism in Oracle
- Deploy mongodb fragment combined with replica set to realize distributed storage of MySQL database files (step 10)
- Centos 7 | mariadb/mysql | [ERROR] InnoDB: Unable to lock ./ibdata1 error: 11
- Fatal: unable to create ‘project_ path/.git/ index.lock ‘: File exists.
- Waiting for another pilot command to release the startup lock
- Using UMI plugin keep alive to realize keep alive state storage in UMI Ant Design
- InnoDB: Unable to lock ibdata1, error: 35
- Forced shutdown of VMware wrokstation error (failed to get exclusive lock on the configuration file —)