java 同步块关键字
Java synchronized keyword is used in multithreading to create a code block that can be executed by only one thread at a time.
Java同步关键字用于多线程中,以创建一个代码块,该代码块一次只能由一个线程执行。
为什么需要同步? (Why do we need Synchronization?)
When we have multiple threads working on a shared entity, the end result might be corrupt. Let’s say we have a simple program to increase the counter variable of the object. This variable is shared across all the threads.
当我们有多个线程在一个共享实体上工作时,最终结果可能会损坏。 假设我们有一个简单的程序来增加对象的计数器变量。 该变量在所有线程之间共享。
package com.journaldev.threads;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class CounterThread implements Runnable {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public void run() {
Random rand = new Random();
try {
Thread.sleep(rand.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
public static void main(String[] args) throws InterruptedException {
CounterThread ct = new CounterThread();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Thread t = new Thread(ct);
threads.add(t);
t.start();
}
// wait for every thread to finish
for (Thread t : threads) {
t.join();
}
System.out.println("Final Count = " + ct.getCount());
}
}
We are using Thread join() method to make sure every thread is dead before we print the final count.
我们正在使用Thread join()方法来确保每个线程都已死,然后再打印最终计数。
We are also using Random class to add some processing time in the run() method.
我们还使用