*Following is the program where 3 objects (obi) each try to print numbers 1 to 10 with corresponding object name (ob1,ob2,ob3).but due to lack of synchronization there output is mixed with one another .make the program synchronized to produce correct output /*

//note:-Do NOT add any DELAY or SLEEP code to the program (other then that is already in program given).

/*Output for Question 4

ob1 : 1

ob1 : 2

ob1 : 3

ob1 : 4

ob1 : 5

ob1 : 6

ob1 : 7

ob1 : 8

ob1 : 9

ob1 : 10

ob2 : 1

ob2 : 2

ob2 : 3

ob2 : 4

ob2 : 5

ob2 : 6

ob2 : 7

ob2 : 8

ob2 : 9

ob2 : 10

ob3 : 1

ob3 : 2

ob3 : 3

ob3 : 4

ob3 : 5

ob3 : 6

ob3 : 7

ob3 : 8

ob3 : 9

ob3 : 10 */

class Print1to10 {

void print1toten(String msg)

{

for(int i=1;i<11;i++)

{

System.out.print(msg + " :" +i);

try{ Thread.sleep(300); }

catch(InterruptedException e)

{ System.out.println("Entrepted"); }

System.out.println("\n");

}

}

}

class StartThread implements Runnable {

String msg;

Print1to10 p;

Thread t;

private StartThread(Print1to10 p,String msg){

p=p;

msg=msg;

t=new Thread(this);

t.start();

}

public void run(){

p.print1toten(msg);

}

}

class synchro {

public static void main(String arg[]){

StartThread ob1=new StartThread(new Print1to10(),"ob1");

StartThread ob2=new StartThread(new Print1to10(),"ob2");

StartThread ob3=new StartThread(new Print1to10(),"ob3");

}

}

can anyone tell me the solution to this problem>??????? :twisted: :eek: :surprised :o

I would synchronize on the output stream.

Regards,

Nate

can anyone tell me the solution to this problem>??????? :twisted: :eek: :surprised :o

No, your task is to find the solution so you'd better go out and do your own homework. :evil: :) :eek: :twisted:

How about using synchronise on the Print1to10 class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.