Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

java thread programming

  Asked By: Harley    Date: Jun 13    Category: Java    Views: 929
  

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 testxxxxtesttesttesttest

question:

why this code is not running concurrently?? look the output...its like , it is
performing sequential execution.but i have created two independent threads and
called start() so it should run concurrently.and surprisingly also, the output
is same for several run, which is not the characteristics of concurrent
execution.whats wrong with this code?how can i make it concurrent?

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Nagaraju Iyaner     Answered On: Jun 13

try putting Thread.yield() in each of your loops as in:

class x extends Thread
{
public void  run()
{
for(int i =0;i<test.count;i++)
{
System.out.println("x");
Thread.yield();
}
}
}
class y extends Thread
{
public void run()
{
for(int i =0;i<test.count;i++)
{
System.out.println("y");
Thread.yield();
}
}
}

public class  test
{
public static final int count = 4;
public static void main(String args[])
{
new x().start();
new y().start();
}
}


result:
x
x
y
x
y
x
y
y

 
Answer #2    Answered By: Tyrone Sanchez     Answered On: Jun 13

This is not about Java, It ' s about your operating system. Your OS has
an process scheduling algorithm that share cpu resource between processes.
So os to os your coding must be change. The simple method is to suspend
your threads  for a while (just 1 milisecond is enough). By this why the active
thread, that we suspend, will go to the end of the cpu request queue and other
threads on queue will
use cpu resource. this works on all platforms. if u dont, your thread  will suck
all the
processing power for itself to the end of its execution.
On unix based platforms u can prefer to use join method for resource sharing.
(not on
m$ platform.maybe 2003 server which is said to be unix kernel based and sco
powered :)
amanin olabilirmi acaba! )whatever.....

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




Tagged: