Skip to content

Commit

Permalink
Thread sync example and concurrent modification exception added
Browse files Browse the repository at this point in the history
  • Loading branch information
ArunrajaShanmugavel committed Jul 1, 2012
1 parent 3293073 commit 6fa36ec
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/ThreadTest/ThreadCreator.java
@@ -0,0 +1,25 @@
package ThreadTest;

public class ThreadCreator extends Thread
{
syncobj a;
int ThrdCnt=0;
public ThreadCreator(syncobj a,int ThrdCnt)
{
this.a = a;
this.ThrdCnt = ThrdCnt;
this.start();
}

public void run()
{
if(ThrdCnt==1||ThrdCnt==2)
{
a.delayAndPrint(ThrdCnt);
a.delayAndPrint2(ThrdCnt);
}

if(ThrdCnt==3)
a.iterateArrayList();
}
}
22 changes: 22 additions & 0 deletions src/ThreadTest/syncmain.java
@@ -0,0 +1,22 @@
package ThreadTest;

public class syncmain {

/* Synchronsed method example */

public static void main(String s[]) throws InterruptedException
{
syncobj obj = new syncobj();

// Synchronised method example
new ThreadCreator(obj,1).join();
new ThreadCreator(obj,2).join();

// ConcrrentModificationException creator
new ThreadCreator(obj,3);
Thread.sleep(2000); // wait till the object is started to iterate
System.out.println("adding to arraylist");
obj.al.add(3);
}

}
65 changes: 65 additions & 0 deletions src/ThreadTest/syncobj.java
@@ -0,0 +1,65 @@
package ThreadTest;

import java.util.ArrayList;
import java.util.Iterator;

public class syncobj {

ArrayList al = new ArrayList();

syncobj()
{
al.add(1);
}

synchronized void delayAndPrint(int cnt)
{
try{
System.out.print("Thread:"+cnt+",Mehod:1-Am in");
Thread.sleep(2000);
System.out.println(", After 2 min out");
}
catch(Exception e)
{
System.out.println("Error-"+e);
}
}

synchronized void delayAndPrint2(int cnt)
{
try{
System.out.print("Thread:"+cnt+",Mehod:2-Am in");
Thread.sleep(2000);
System.out.println(", After 2 min out");
}
catch(Exception e)
{
System.out.println("Error-"+e);
}
}

void iterateArrayList()
{
try
{
System.out.println("starting iterate");
Iterator b= al.iterator();
while(b.hasNext())
{
try
{
Thread.sleep(5000);
b.next();
} catch (InterruptedException e)
{
System.out.println(e);
}
}
System.out.println("ending iterate");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

0 comments on commit 6fa36ec

Please sign in to comment.