How do I create a thread synchronized block?

The objective of thread synchronization is to ensure that when several threads want access to a single resource, only one thread can access it at any given time.

You can manage synchronization of your program at method level (synchronized method) or at block level (synchronized block). To make a block of code synchronized you can use the synchronized keyword.

The example below show how you can use the synchronized keyword.

Incrementor

package org.kodejava.example.lang.thread;

public class Incrementor {
    private int count;

    // A synchronized method example.
    public synchronized void increment(int value) {
        count += value;
        System.out.println(Thread.currentThread().getName() +
                ": inc >>> " + count);
    }

    public void decrement(int value) {
        // A synchronized block example the use the current object instance
        // as the monitor object.
        synchronized (this) {
            count -= value;
            System.out.println(Thread.currentThread().getName() +
                    ": dec >>> " + count);
        }
    }
}

IncrementThread

package org.kodejava.example.lang.thread;

public class IncrementThread implements Runnable {
    private Incrementor incrementor;

    public IncrementThread(Incrementor incrementor) {
        this.incrementor = incrementor;
    }

    public void run() {
        for (int i = 1; i <= 5; i++) {
            incrementor.increment(i * 10);
            incrementor.decrement(i * 2);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

IncrementorDemo

package org.kodejava.example.lang.thread;

public class IncrementorDemo {
    public static void main(String[] args) {
        Incrementor incrementor = new Incrementor();

        Thread t1 = new Thread(new IncrementThread(incrementor), "T1");
        Thread t2 = new Thread(new IncrementThread(incrementor), "T2");

        t1.start();
        t2.start();
    }
}

Here an example result printed by the program:

T1: inc >>> 10
T1: dec >>> 8
T2: inc >>> 18
T2: dec >>> 16
T1: inc >>> 36
T1: dec >>> 32
T2: inc >>> 52
T2: dec >>> 48
T1: inc >>> 78
T1: dec >>> 72
T2: inc >>> 102
T2: dec >>> 96
T1: inc >>> 136
T1: dec >>> 128
T2: inc >>> 168
T2: dec >>> 160
T1: inc >>> 210
T1: dec >>> 200
T2: inc >>> 250
T2: dec >>> 240

How do I set and get the name of a thread?

You can assign a name to thread instance by using the setName() method and get the name of the thread using the getName() method. The naming support is also available as a constructor of the Thread class such as Thread(String name) and Thread(Runnable target, String name).

package org.kodejava.example.lang;

public class ThreadNameDemo extends Thread {
    public ThreadNameDemo() {
    }

    public ThreadNameDemo(String name) {
        super(name);
    }

    @Override
    public void run() {
        // Call getName() method to get the thread name of this
        // thread object.
        System.out.println("Running [" + this.getName() + "]");
    }

    public static void main(String[] args) {
        Thread thread1 = new ThreadNameDemo();
        thread1.setName("FOX");
        thread1.start();

        Thread thread2 = new ThreadNameDemo("DOG");
        thread2.start();
    }
}

How do I use join method to wait for threads to finish?

If you want a thread to work until another thread dies, you can join the thread onto the end of the another thread using the join() method. For example, you want thread B only work until thread A completes its work, then you want thread B to join thread A.

package org.kodejava.example.lang;

public class ThreadJoin implements Runnable {
    private int numberOfLoop;

    private ThreadJoin(int numberOfLoop) {
        this.numberOfLoop = numberOfLoop;
    }

    public void run() {
        System.out.println("[" +
            Thread.currentThread().getName() + "] - Running.");

        for (int i = 0; i < this.numberOfLoop; i++) {
            System.out.println("[" +
                Thread.currentThread().getName() + "] " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("[" +
            Thread.currentThread().getName() + "] - Done.");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadJoin(10), "FirstThread");
        Thread t2 = new Thread(new ThreadJoin(20), "SecondThread");

        try {
            // start t1 and waits for this thread to die before
            // starting the t2 thread.
            t1.start();
            t1.join();

            // start t2
            t2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

How do I set the priority of a thread?

Threads always run with some priority, usually represented as a number between 1 and 10 (although in some cases the range is less than 10). A thread gets a default priority that is the priority of the thread of execution that creates it.

But, you can also set a thread’s priority directly by calling the setPriority() method on a Thread instance. One thing to remember about thread priorities is never rely on thread priorities, because thread-scheduling priority behavior is not guaranteed.

package org.kodejava.example.lang;

public class ThreadPriority extends Thread {
    private String threadName;

    ThreadPriority(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        System.out.println("Running [" + threadName + "]");
        for (int i = 1; i <= 10; i++) {
            System.out.println("[" + threadName + "] => " + i);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThreadPriority thread1 = new ThreadPriority("First");
        ThreadPriority thread2 = new ThreadPriority("Second");
        ThreadPriority thread3 = new ThreadPriority("Third");
        ThreadPriority thread4 = new ThreadPriority("Fourth");
        ThreadPriority thread5 = new ThreadPriority("Fifth");

        // set thread1 to minimum priority = 1
        thread1.setPriority(Thread.MIN_PRIORITY);

        // set thread2 to priority 2
        thread2.setPriority(2);

        // set thread3 to normal priority = 5
        thread3.setPriority(Thread.NORM_PRIORITY);

        // set thread4 to priority 8
        thread4.setPriority(8);

        // set thread5 to maximum priority = 10
        thread5.setPriority(Thread.MAX_PRIORITY);

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}

How do I get the currently executing thread?

To get the currently executing thread, use the static currentThread() method of the Thread class. This method returns a reference of the currently executing thread object.

package org.kodejava.example.lang;

public class GetCurrentThreadDemo {
    public static void main(String[] args){
        // Get the currently executing thread object
        Thread thread = Thread.currentThread();
        System.out.println("Id      : " + thread.getId());
        System.out.println("Name    : " + thread.getName());
        System.out.println("Priority: " + thread.getPriority());
    }
}

The code snippet print the following output:

Id      : 1
Name    : main
Priority: 5