Get the App
SLTechnology News&Howtos  ›  Development  › 

How to share data among Java multithreads

Shulou Source: shulou.com Published: 2022-06-02 20:17:53 11月17日 Update

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 [)

Tags: Thread data module object variable different code method multiple instance same two processing encapsulation account system scope between transaction balance Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi OPPO Reno Docker MariaDB macOS