T
Timo Nentwig
Hi!
Below I do start Thread t1 before t2. t1 tries to call print1() on a
Printer object and t1 print2() but only the first will success since it
obtains a lock on the Printer object. I'm surprised that although t1 is
started first the code prints "2". If I put a sleep(5) between the
starting of the threads t1 wins the race.
Can somebody explain?
public class SyncThreadTest
{
public static void main( String[] args )
{
new SyncThreadTest().go();
}
private void go()
{
Thread t1 = new Thread( new Runner( 1 ) );
Thread t2 = new Thread( new Runner( 2 ) );
System.out.println(t1.toString());
t1.start();
System.out.println(t2.toString());
t2.start();
}
class Runner implements Runnable
{
int i = 0;
public Runner( int i )
{
this.i = i;
}
public void run()
{
// Printer p = Printer.getInstance();
Printer p = new Printer();
// synchronized( p )
// synchronized( Printer.class )
synchronized( p.MUTEX )
{
while( true )
{
System.out.println(toString());
if( i == 1 ) p.print1();
else p.print2();
try
{
Thread.sleep( 500 );
}
catch( InterruptedException e )
{
}
}
}
}
}
}
class Printer
{
private static final Printer instance = new Printer();
public static final Object MUTEX = new Object();
public static Printer getInstance()
{
return instance;
}
public synchronized void print1()
{
System.out.println( 1 );
}
public synchronized void print2()
{
System.out.println( 2 );
}
}
Below I do start Thread t1 before t2. t1 tries to call print1() on a
Printer object and t1 print2() but only the first will success since it
obtains a lock on the Printer object. I'm surprised that although t1 is
started first the code prints "2". If I put a sleep(5) between the
starting of the threads t1 wins the race.
Can somebody explain?
public class SyncThreadTest
{
public static void main( String[] args )
{
new SyncThreadTest().go();
}
private void go()
{
Thread t1 = new Thread( new Runner( 1 ) );
Thread t2 = new Thread( new Runner( 2 ) );
System.out.println(t1.toString());
t1.start();
System.out.println(t2.toString());
t2.start();
}
class Runner implements Runnable
{
int i = 0;
public Runner( int i )
{
this.i = i;
}
public void run()
{
// Printer p = Printer.getInstance();
Printer p = new Printer();
// synchronized( p )
// synchronized( Printer.class )
synchronized( p.MUTEX )
{
while( true )
{
System.out.println(toString());
if( i == 1 ) p.print1();
else p.print2();
try
{
Thread.sleep( 500 );
}
catch( InterruptedException e )
{
}
}
}
}
}
}
class Printer
{
private static final Printer instance = new Printer();
public static final Object MUTEX = new Object();
public static Printer getInstance()
{
return instance;
}
public synchronized void print1()
{
System.out.println( 1 );
}
public synchronized void print2()
{
System.out.println( 2 );
}
}