import java.io.*;
import java.util.concurrent.*;

public class InstanceSync
{
	static int finished=0;
	static final int ThreadNumber=2;
	static SynClass A=new SynClass(), B=new SynClass();
	public static void main(String argv[])
	{		
		MyThread threads[]=new MyThread[ThreadNumber];
		for (int i=0; i<ThreadNumber; i++)
		{
			threads[i]=new MyThread(i);
			threads[i].start();			
		}

			
		System.out.println(" two threads started");
		while (finished<ThreadNumber)
		{
			try
			{
				//System.out.println("finished="+finished+"sleeping...");
				Thread.sleep(1000);
			}
			catch (Exception er)
			{
			}
		}
	}

	static class SynClass
	{
		synchronized void funcA()
		{
			int counter=0;
			while (counter<5)
			{
				System.out.println("func A");
				try
				{
					Thread.sleep(1000);
				}
				catch (Exception er)
				{
				}
				counter++;
			}
			finished++;
		}

		synchronized void funcB()
		{
			int counter=0;
			while (counter<5)
			{
				System.out.println("func B");
				try
				{
					//Thread.sleep(1000);
				}
				catch (Exception er)
				{
				}
				counter++;
			}
			finished++;
			
		}	
	}

	static class MyThread extends Thread
	{
		int myID;
		public MyThread(int id)
		{
			myID=id;
		}
		public void run() 
		{
			try
			{						
				if (myID%2==0)
				{
					
					A.funcA();
				}
				else
				{
					//B will wait a to enter.
					Thread.sleep(1000);
					//A.funcB();
					B.funcB();
				}
				
			}
			catch (Exception er)
			{
			}
		}
	}
			
}	

