how do i return a value from run method say return a string
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   abhay_sahai
Posted On:   Monday, July 22, 2002 03:20 AM

I have a thread running whic does some work, now I want to pass some values to it so I used a custom Thread class. but this thread manipulates the values and I want the run method to return those values. as java has no pointers How??

Re: how do i return a value from run method say return a string

Posted By:   Gautam_Marwaha  
Posted On:   Tuesday, July 23, 2002 12:04 AM

One way to return back some value from spawned threads to the object starting the threads is to pass the reference of the object to all spawned threads in the constructor. This object is set as a member in the thread implementation class. In the run method of the spawned threads, some value may be returned back by calling a method on the object (member variable). Note that this method will be called from multiple threads so may need synchronized access.

Re: how do i return a value from run method say return a string

Posted By:   Simon_Ablett  
Posted On:   Monday, July 22, 2002 05:20 AM

Give the class a private attribute of the appropriate type and provide an appropriate accessor. A very simplistic solution using an 'int' is given below. It should give you a rough idea of how to proceed.

public class T1 extends Thread
{
public static void main( String [] args )
{
T1 t1 = new T1();

t1.start();

System.out.println("Value is: ("+t1.getVal()+")");

System.exit(0);
}

public T1( )
{
mMyVal = 60;
}

public void run( )
{
mMyVal = 77;
}

public int getVal( )
{
return mMyVal;
}

private int mMyVal;
}

Regards.

Re: how do i return a value from run method say return a string

Posted By:   Anonymous  
Posted On:   Monday, July 22, 2002 04:56 AM

There are more that one way to do this.

One is to encapsulate the run method of the thread with your
own custom method. This is using Object Oriented
programming instead of pointers. Here is an example:


public class TestValues extends Thread{


private String string;


public TestValues(){


string = "";


}


public String runThread(String values){


/*Here you use your custome method to encapsulate the run

method, this allows you to create differend methods that
uses the run method to do different tasks.*/



try{

string = values;


run();

}

catch(Exception exc){string = "error:" + exc.getMessage();}


return string;

}




public void run(){

for(int i = 0; i < 10; i++)

string += ", " + Integer.toString(i);


}



public static void main(String arg[]){

TestValues test = new TestValues();



System.out.println(test.runThread("Test string"));


}



}


This my seem like alot of code but encapsulating objects to
extend there functionality is the basics of Object
Orientated programming and will provide advantages to
your projects in the long run.

About | Sitemap | Contact