Synchronized Static Block Tutorial

This tutorial is a companion to my Synchronized Static Method Tutorial and will demonstrate applying the synchronized keyword to a code block to make our static method thread safe. You will need to watch the other tutorial prior to this one in order to follow along - I'll be giving the abridged explanation.

Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>md SynchronizedStaticBlock
C:\Java>cd SynchronizedStaticBlock

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.

import java.util.*;
class SynchronizedStaticBlock {
    public static void main(String args[]) {
        for (int i = 0; i < 100; i++) {
            new NumberThread(i);
        System.out.println("Active threads: "+Thread.activeCount());

class StaticList {
    private static ArrayList<Integer> numberList = new ArrayList<>();
    static void addToList(Integer number) {
        numberList.add(number);  // ArrayList add() method in addToList is not thread-safe - problems
    static void displayList() {

class NumberThread implements Runnable {
    private int number = 0;

    NumberThread(int number){
        this.number = number;
        new Thread(this).start();

    public void run() { // this is where the new thread starts

Now switch back to the command prompt (CMD) and type in javac and press Enter.
Now type in java SynchronizedStaticBlock and press Enter.

C:\Java\SynchronizedStaticBlock>java SynchronizedStaticBlock
see video for results

Final thoughts

In my next tutorial I will demonstrate how to apply the synchronized keyword to instance methods.