1. Principle analysis
Atomicinteger is thread safe, and autoincrement is thread safe.
2. Code examples
package com.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class TasksTest extends Thread {
private static AtomicInteger atomic = new AtomicInteger(1);
private int id;
public TasksTest(int id) {
this.id = id;
}
@Override
public void run() {
while (atomic.get() <= 12) {
while (atomic.get() % 3 == id) {
System.out.println("thread_" + id + " output:" + atomic.get());
atomic.incrementAndGet();
}
}
}
public static void main(String[] args) {
Thread thread0 = new TasksTest(0);
Thread thread1 = new TasksTest(1);
Thread thread2 = new TasksTest(2);
ExecutorService exec = Executors.newFixedThreadPool(3);
exec.submit(thread0);
exec.submit(thread1);
exec.submit(thread2);
exec.shutdown();
}
}
Read More:
- Java uses single thread pool to realize multi thread sequential execution (non alternating, non synchronous)
- The thread implementation of timer in Java
- Java uses class array to report error Exception in thread “main” java.lang.NullPointerException solution
- [Solved] Docker Elasticsearch8.4.0 Error: Exception in thread “main” java.nio.file.FileSystemException
- [Solved] qrcode-error: Exception in thread “main” java.lang.NoClassDefFoundError…
- RSA Decryption Error: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
- [Solved] Exception in thread “main“ java.lang.NoSuchFieldError: level
- Jmeter Error: ERROR o.a.j.JMeter: Uncaught exception in thread Thread[AWT-EventQueue-0,6,main]
- [Solved] java.sql.SQLException: Table ‘xxx.hibernate_sequence’ doesn’t exist
- [Solved] Hadoop Error: Exception in thread “main“ java.io.IOException: Error opening job jar: /usr/local/hadoop-2.
- Implementation of retrial mechanism in Java
- Ternary operator in Java?: error: not a statement
- How to Close the Current Form in JAVA Swing
- Mybatis query error: Exception in thread “main” org.apache.ibatis.exceptions.PersistenceException…
- [Solved] java Internal error in the mapping processor java.lang.NullPointerException
- [Solved] java Internal error in the mapping processor java.lang.NullPointerException
- [Solved] Error: A JNI error has occurred, please check your installation and try again Exception in thread
- [Solved] Hibernate Error: java.lang.StackOverflowError at java.lang.Integer.toString(Integer.java:402)
- [Solved] Initialization of anonymous inner class member variable causes java.lang.stackoverflowerror
- [PROJECT] itdage java to get the weather and send text messages