Threadvsobject

This program illustrates the difference between a thread object and a synchronization object.

/*
 *  This program illustrates the difference between a thread object and
 *  a synchronization object.
 */
 
public class ThreadVsObject
{
 
    // a synchronization class
    static class SynchClass
    {
        int x = 1;
 
        public synchronized void foo(int callerid)
        {
            System.out.println(callerid + " is calling SynchClass.foo");
            System.out.println("this.x is " + this.x);
            // get a pointer to the thread that's running this code:
            ThreadClass ct = (ThreadClass) Thread.currentThread();
            // note the type down-casting from Thread to T
            System.out.println("Thread.currentThread().x is " + ct.x);
        }
    }
 
    // a thread class:
    static class ThreadClass extends Thread
    {
        int x = 2;
 
        SynchClass a0;
 
        int id;
 
        public ThreadClass(int id, SynchClass x)
        {
            a0 = x;
            this.id = id;
        }
 
        public void run()
        {
            try
            {
                for (int i = 0; i < 4; i++)
                {
                    a0.foo(id);
                    Thread.sleep(1000); // 1 second delay
                }
            } catch (InterruptedException ie)
            {
                System.out.println(ie);
            }
        }
    }
 
    public static void main(String[] args) throws InterruptedException
    {
        SynchClass syn = new SynchClass();
        ThreadClass t1, t2;
        t1 = new ThreadClass(1, syn);
        t2 = new ThreadClass(2, syn);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.