Archive

Posts Tagged ‘thread’

Java thread tutorial

October 18th, 2009 CertPal 1 comment

j_thread_locksIf you are a newbie to working with java threads, this post will help you. Certifications like the SCJP require you to understand java threads to a fair degree. Threads behavior can be difficult to understand even for experienced programmers, so I will try to present some examples which will help candidates identify how threads wait / lock and synchronize.

Lets cut the chit chat and jump into a problem. A program increments a counter in a for loop as shown below.

Synchronizing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class StaticSync
{
    public static final Object s_lock = new Object();
    public static int s_counter=0;
    public static void main(String... args)
    {
        new StaticSync().go();
    }
 
    public void go()
    {
        for(int iCounter=0; iCounter<50; iCounter++)
        {
            Thread thread = new Thread(new Incrementer(new StaticSync()));
            thread.start();
        }
    }
}
 
class Incrementer implements Runnable
{
    StaticSync m_staticSync=null;
    public Incrementer(StaticSync staticSync_INP)
    {
        m_staticSync = staticSync_INP;
    }
 
    public void run()
    {
        synchronized (m_staticSync.s_lock)
        {
            m_staticSync.s_counter++;
            System.out.println(m_staticSync.s_counter);
        }
    }
}

This program is pretty simple. This is the sort of code that you can expect on the SCJP exam. Advanced versions of the code above can also appear by adding notify() wait() sleep() etc into the picture. Let us concentrate on the program for now. What can be guaranteed about the output of this program ?

Categories: Java certifications Tags: , ,