In Java, dealing with the automatic acquisition of order numbers for both outbound and inbound orders is usually involved in concurrent control in a multi-threaded environment. To ensure the uniqueness and continuity of order numbers, we can use a variety of strategies, such as database self-increment ID, distributed locking, or concurrent tool classes that utilize JavaAtomicLong
wait. Here, I will provide aAtomicLong
Simple example for stand-alone environments.
1. Scene description
Suppose we have a simple inventory management system that needs to handle both outbound and inbound operations, and each operation requires a unique order number. We will useAtomicLong
to generate these order numbers because it provides thread-safe operations.
2. Solution
(1)Define order number generator:useAtomicLong
to ensure the thread-safe generation of order numbers.
(2)Simulate outbound and inbound operations: Use threads to simulate concurrent operations, each thread will obtain a unique order number from the order number generator when executing.
3. Sample code
import ; public class OrderNumberGenerator { private static final AtomicLong orderIdGenerator = new AtomicLong(1); // Assume that starts from 1 // Threading tasks, simulate outbound or inbound static class OrderTask implements Runnable { private final String type; // Out or into the warehouse public OrderTask(String type) { = type; } @Override public void run() { long orderId = (); // Threads safely obtain the next order number (().getName() + " implement " + type + "Operation, Order Number:" + orderId); } } public static void main(String[] args) { // Create and start multiple threads to simulate concurrent operations Thread t1 = new Thread(new OrderTask("Out of warehouse"), "Outbound thread 1"); Thread t2 = new Thread(new OrderTask("Into the warehouse"), "Initial thread 1"); Thread t3 = new Thread(new OrderTask("Out of warehouse"), "Out-out thread 2"); Thread t4 = new Thread(new OrderTask("Into the warehouse"), "Initial thread 2"); (); (); (); (); // Wait for all threads to complete try { (); (); (); (); } catch (InterruptedException e) { (); } } }
4. Explanation
(1)AtomicLong
: This is a provided atomic operationlong
Variable class, used to generate a unique order number in a multi-threaded environment.
(2)Threading tasks:OrderTask
The class has been implementedRunnable
Interface, used to simulate outbound or inbound operations. Every task will be fromorderIdGenerator
Get a unique order number in
(3)Main function:existmain
In the method, we create four threads to simulate concurrent operations and start them. usejoin()
The method waits for all threads to complete to ensure that the main thread ends after outputting all order numbers.
5. Things to note
(1) If the system needs to handle order number generation in a distributed environment, it may be necessary to consider using the database's self-increment ID, Redis' atomic operation or distributed ID generation algorithm (such as the snowflake algorithm Snowflake), etc.
(2) In high concurrency scenarios,AtomicLong
The performance may not be optimal, but for simple stand-alone applications, it is efficient and easy to implement.
6. Complete Java code examples
This complete Java code example shows how to use itAtomicLong
To generate a unique order number in a multi-threaded environment. This example simulates outbound and inbound operations in a simple inventory management system, each of which will be fromAtomicLong
Get a unique order number in
import ; // Thread task class, used to simulate outbound or inbound operationsclass OrderTask implements Runnable { private final String type; // Out or into the warehouse private final AtomicLong orderIdGenerator; // Order number generator public OrderTask(String type, AtomicLong orderIdGenerator) { = type; = orderIdGenerator; } @Override public void run() { // Threads safely obtain the next order number long orderId = (); // Simulate outbound or inbound operations (just print information here) (().getName() + " implement " + type + "Operation, Order Number:" + orderId); } } public class OrderSystem { // Order number generator, assuming it starts from 1 private static final AtomicLong orderIdGenerator = new AtomicLong(1); public static void main(String[] args) { // Create and start multiple threads to simulate concurrent operations Thread t1 = new Thread(new OrderTask("Out of warehouse", orderIdGenerator), "Outbound thread 1"); Thread t2 = new Thread(new OrderTask("Into the warehouse", orderIdGenerator), "Initial thread 1"); Thread t3 = new Thread(new OrderTask("Out of warehouse", orderIdGenerator), "Out-out thread 2"); Thread t4 = new Thread(new OrderTask("Into the warehouse", orderIdGenerator), "Initial thread 2"); // Start all threads (); (); (); (); // Wait for all threads to complete (optional, depending on whether you need to wait for all operations to complete before continuing) try { (); (); (); (); } catch (InterruptedException e) { (); } // If you don't need to wait for all threads to complete, you can omit the above join call // ...Perform other operations } }
In this example,OrderTask
The class is an implementationRunnable
The thread task of the interface, which accepts an operation type (outbound or inbound) and aAtomicLong
The instance serves as an order number generator. existrun
In the method, it first starts fromorderIdGenerator
Get a unique order number in it, and then simulate the outbound or inbound operation (there is simply a message printed here).
OrderSystem
Classicmain
Method creates four threads, each executing a different oneOrderTask
Example. After these threads are started, they will perform out-of-warehouse or in-warehouse operations concurrently and fromorderIdGenerator
Get the unique order number in .
Note that it has been usedAtomicLong
, so even in a multi-threaded environment, the generation of order numbers is thread-safe and does not require additional synchronization control.
also,main
In the methodjoin
The call is optional and it is used to wait for all threads to complete. If our application can continue to perform other operations after starting these threads without waiting for them to complete, then these can be omittedjoin
Called. However, in this example, I keep them to show how to wait for all threads to complete.
This is the article about solving the problem of automatically obtaining order numbers for Java at the same time. For more related Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!