How to share data among Java multithreads
This article mainly introduces how to share data between Java multithreads, which is very detailed and has certain reference value. Friends who are interested must finish reading it.
1. Thread-wide shared variables
Multiple business modules operate on the same static variable to ensure that each module operates its own corresponding variable object in different threads.
Public class ThreadScopeSharaData {private static int data = 0; public static void main (String [] args) {for (int I = 0; I 0) {ticket--; System.out.println ("current votes:" + ticket);}
(2) if each thread executes different code, you need to use different Runnable objects, for example, design 2 threads. One thread adds 1 to j and the other to j minus 1, the bank deposit and withdrawal system.
Public class MultiThreadShareData {private int j; public static void main (String [] args) {MultiThreadShareData multiThreadShareData = new MultiThreadShareData (); for (int iTuno [)