In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to use Java multithreading to achieve cumulative counting, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Title
A given count=0; allows 5 threads to add up to 1000 concurrently
Train of thought
Create a class MyRunnable that implements Runnable (you can also inherit the Thread class)
Define a common variable count with an initial value of 0, which can be accessed by all five threads
Create 5 threads and increment count to 1000 concurrently
Be careful
This section notes the difference between the Thread and Runnable classes, which are threaded classes that can be run directly by new Thread () .start. The Runnable class is a task class, which requires a thread to host the task and runs the task through new Thread (new Runnable ()). Start ().
Method
Method one
Put the count public variable into the class member variable of the test class Test, take the MyRunnable class as the inner class of the Test class, and create 5 threads in the main method of the Test class to achieve accumulation.
Code
Public class Test {/ / public variable int count=0; public static void main (String [] args) {/ / new a class Test test=new Test () that implements Runnable; / / create 5 tasks MyRunnable myRunnable1=test.new MyRunnable (); MyRunnable myRunnable2=test.new MyRunnable (); MyRunnable myRunnable3=test.new MyRunnable (); MyRunnable myRunnable4=test.new MyRunnable (); MyRunnable myRunnable5=test.new MyRunnable (); / / create 5 threads new Thread (myRunnable1). Start (); new Thread (myRunnable2). Start () New Thread (myRunnable3). Start (); new Thread (myRunnable4). Start (); new Thread (myRunnable5). Start ();} / / create a class class MyRunnable implements Runnable {public void run () {while (true) {/ / locking the entire MyRunnable class synchronized (MyRunnable.class) {if (count > = 1000) {break;} System.out.println (Thread.currentThread (). GetName () +: count: "+ (+ + count)). / / when testing, it is easier for threads to switch Thread.yield ();}
Method two
There is no problem with the above code, the successful implementation of 5 threads accumulate count to 1000, and then we will modify the above code slightly.
5 threads perform 5 tasks, modified to 5 threads to perform the same task.
Modify synchronized (MyRunnable.class) to synchronized (this)
Code
Public class Test {/ / common variable int count=0; public static void main (String [] args) {/ / new a class Test test=new Test () that implements Runnable; / / create a task MyRunnable myRunnable1=test.new MyRunnable (); / / MyRunnable myRunnable2=test.new MyRunnable (); / / MyRunnable myRunnable3=test.new MyRunnable (); / / MyRunnable myRunnable4=test.new MyRunnable (); / / MyRunnable myRunnable5=test.new MyRunnable (); / / create 5 threads for (int item0) (break) {break } System.out.println (Thread.currentThread (). GetName () + ": count:" + (+ + count)); / / when testing, threads are easier to switch Thread.yield ();}
There is no problem with the above code, successfully implementing 5 threads accumulating count to 1000.
Although the result is the same, the code implementation is different. Code one creates five MyRunnable objects, and code two creates only one MyRunnable object. The locks used when considering concurrency are different.
Although the locks in Code 1 and Code 2 are different in synchronized, the purpose is that the locks in parentheses are constant.
Synchronized (this) means that the lock is a this object, and this can be used in code 2 because several threads use the same this.
Synchronized (MyRunnable.class) means that the lock is MyRunnable.class.this, because the MyRunnable.class.this is the class loaded into the static method area, which is always unchanged, and can be used in code 1, and of course code 2 can be written in the same way.
Code 1 and Code 2 can use a more general way to new a lock object, which can be placed in the class member variable, plus static can always be stored. If defined as public static Object lock=new Object (); both Code 1 and Code 2 can be locked using synchronized (lock). Synchronized (this) is mainly because of the convenience of writing.
Method three
Use AtomicInteger class to achieve multi-thread accumulation, AtomicInteger class is thread-safe, the advantage of using it is that we do not need to write the Synchronized keyword in the code, these things are left to it to do.
Code
Public class Test {static CountDownLatch cdl=new CountDownLatch (1000);; static AtomicInteger ai=new AtomicInteger (0); public static void main (String [] args) throws InterruptedException {ExecutorService exec=Executors.newFixedThreadPool (100); for (int I = 0; I < 1000; iTunes +) {exec.execute (new Runnable () {@ Override public void run () {System.out.println (Thread.currentThread (). GetName () + ":" + ai.getAndIncrement ()); cdl.countDown () });} cdl.await (); System.out.println (ai.get ()); exec.shutdown ();}}
The CountDownLatch class is used in the code. The usage is to set an initial value of 1000 for it, and then execute the countDown method in different threads. Each time, the initial value-1 method is to wait until the initial value is reduced to 0, stop waiting, otherwise keep waiting.
Thank you for reading this article carefully. I hope the article "how to use the multithreading of Java to achieve cumulative counting" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.