An example of multithread summation in Java
This article mainly explains "Java multithreaded summation example explanation", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn the "Java multithreaded summation examples to explain" it!
Write a program that starts 100threads, each thread adds 1 to a variable sum with an initial value of 0, and needs to pass sum by referencing each thread. In order to pass through drinking, define an Integer wrapper object to accommodate sum, design the program in synchronous and asynchronous ways, and view the results.
Public class Test implements Runnable {public static void main (String [] args) {for (int I = 0; I)
< 100; i++) { // 创建100个线程 Test line = new Test(); Thread t = new Thread(line, i + ""); t.start(); } } public void run() { // 线程 for (int i = 0; i < 10; i++) { //每条线程输出的次数 如果你是10次 100个线程,如果同步,sum 应该是1000 try { sum.list(); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } class sum { static Integer sum = 0; public synchronized static void list() { //synchronized 代表线程同步, 如果去掉.就会不同步 sum++; System.out.println("我是线程" + Thread.currentThread().getName() + " sum--------->"+ sum);}} at this point, I believe you have a deeper understanding of the" Java multithreaded summation example explanation ", might as well come to the actual operation! here is the website, more related content can enter the relevant channels to query, follow us, continue to learn!