1. Principle
Synchronized thread synchronization
Notify() calls up the thread
The wait() thread waits
2. Code examples
package com.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TasksTestSync extends Thread {
private static Integer num = 0;
private int id;
public TasksTestSync(int id) {
this.id = id;
}
@Override
public void run() {
while (num < 12) {
synchronized (TasksTestSync.class) {
num = num + 1;
System.out.println("thread_" + id + " num:" + num);
TasksTestSync.class.notify();
try {
TasksTestSync.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Thread thread0 = new TasksTestSync(0);
Thread thread1 = new TasksTestSync(1);
ExecutorService exec = Executors.newFixedThreadPool(3);
exec.submit(thread0);
exec.submit(thread1);
exec.shutdown();
}
}
3. Implementation results
Read More:
- Java uses lock to realize multithread sequential alternate execution mode 2
- Global lock, table lock and row lock in MySQL
- The difference between sleep() and wait() in Java
- Java 8 Stream – Read a file line by line
- Caused by: java.net.SocketException : connection reset or caused by: java.sql.SQLRecoverableException solve
- 43. Implementation of the shortest code of multiply strings | Java
- Design and implementation of music website based on Java
- Group by operator of hive execution plan
- Unity Cursor Lock& Camera Lock
- Implementation of tupledesc and tuple in mit6.830 lab1 / exercise 1
- When linux installs rpm, it prompts: can’t create transaction lock on /var/lib/rpm/.rpm.lock error
- Two kinds of errors caused by root / lack of execution permission x
- Divide in [JavaEE] BigDecimal, divisor cannot be 0. java.lang.ArithmeticException : / by zero
- android Caused by: java.util.ConcurrentModificationException
- Pytorch — nn.Sequential () module
- Lock mechanism in Oracle
- Why do we not need to write implementation classes in mybatis to get the objects we need
- Implementation of screen cleaning in Python idle
- Implementation of Python switch / case statements
- Python switch / case statement implementation method