Click here to Skip to main content
15,996,429 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Java
class Thread1 extends Thread
{
Thread1(String s)
{
super(s);
start();
}
public synchronized void run()
{
for(int i=0;i<4;i++)
{
  System.out.println(Thread.currentThread().getName()+"is running");
   try
   {
    Thread.sleep(1000);
   }
   catch(Exception e){}
}
}
}

Java
class Thread2 extends Thread
{
 Thread2(String s)
 {
super(s);   
start();
 }
  public void run()
  {
    sum();
   }
   public synchronized void sum()
      { 
      for(int i=0;i<4;i++)
      {
      System.out.println(Thread.currentThread().getName()+"is    running sum"); 
      try
       {
        Thread.sleep(1000);
       }
      catch(Exception e){}
      }
      }
}

Java
class ThreadApply
{
public static void main(String... args)
{
Thread1 t1 = new Thread1("thread 1");
Thread2 t2 = new Thread2("thread 2");
}
}

When i execute the above program i got the output

thread 1is running
thread 2is running sum
thread 1is running
thread 2is running sum
thread 1is running
thread 2is running sum
thread 1is running
thread 2is running sum

While according to the rule of synchonization only one thread is executed at a time in synchronized method than why the output like this...

Torsten - added some code blocks to make this readable
Posted
Updated 21-Dec-12 23:39pm
v2

1 solution

..because the other Thread is sleeping. That the chance for the opposite Thread to run.

http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html[^]

It's better visible like this:
Java
package com.cp;

public class ThreadApply {
	
	public int iCount=0;
	
	public ThreadApply(){
		Thread1 t1 = new Thread1("thread 1"); // ++
		Thread2 t2 = new Thread2("thread 2"); // --
	}
	
	
	
	public static void main(String... args) {
		new ThreadApply();
	}
	
	
	private class Thread1 extends Thread {
		Thread1(String s) {
			super(s);
			start();
		}
	
		public synchronized void run() {
			for (int i = 0; i < 200; i++) {
				iCount++;
				System.out.println(Thread.currentThread().getName() + " iCount:" + iCount);
				try {
//					Thread.sleep(1000); // no sleeping for you, Mr. Thread1
				} catch (Exception e) {
				}
			}
		}
	}
	
	private class Thread2 extends Thread {
		Thread2(String s) {
			super(s);
			start();
		}
	
		public void run() {
			sum();
		}
	
		public synchronized void sum() {
			for (int i = 0; i < 20; i++) {
				iCount--;
				System.out.println("\t"  + Thread.currentThread().getName() + " iCount:" + iCount);
				try {
					Thread.sleep(100);
				} catch (Exception e) {
				}
			}
		}
	}


}


Thread1 is running at high speed - Thread2 is waiting until Thread1 has releases the lock on the referenced value iCount.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900