Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

problem in thread concurrency

  Asked By: Craig    Date: Oct 19    Category: Java    Views: 530
  

code
-----

import java.lang.*;
class x extends Thread
{

public void run()
{
for(int i =0;i<4;i++) System.out.println("x");
}


}


class test extends Thread
{

public void run()
{
for(int i =0;i<4;i++) System.out.println("test");
}


public static void main(String args[])

{
x th1 = new x();
test th2 = new test();


th1.start();
th2.start();


}


}

output:
--------
>java test
x
x
x
x
test
test
test
test

why this code is not obeying concurrency?? i have created 2 threads
and called start()....but these two threads are doing sequential
opeartion !!( as you see the output...outputs are same for several
run).


where i am wrong? how can i achieve concurrency ??

Share: 

 

4 Answers Found

 
Answer #1    Answered By: Dennis Hayes     Answered On: Oct 19

The only problem  with your code  is the max val of i in the loop.
Increase it to a high value, you'll see the results. Hope the issue
is self-explanatory. You first thread  completes much before the
second thread could start  even. Thatz why you see them printed
sequentially.

 
Answer #2    Answered By: Canan Kaya     Answered On: Oct 19

Your program is obeying thread  rule
processor executes one instrution at a time
it runs the program and now it depends upon OS how much clock cycles it give to
a program ( thread)

Try increasing the loop

you will see output  like

some "x" then some "test" then some "x" then some "test" ..............

 
Answer #3    Answered By: Steve Boyd     Answered On: Oct 19

If i am n't wrong, then we need run() method to start  the thread;;;;

 
Answer #4    Answered By: Raul Clark     Answered On: Oct 19

The result is fine one.
You have to add command
sleep(200);

 
Didn't find what you were looking for? Find more on problem in thread concurrency Or get search suggestion and latest updates.




Tagged: