开发者

I want the main method to print out the value x, which is returned by running threads

I want the main method to print out the value x, which is returned by running threads. How can I do it? Hope that my question makes sense.

  import java.*;

  public class ServerStudentThread extend开发者_开发问答s Thread 
  {

        public ServerStudentThread(Socket x) {  
       client = x;  
    }

        public void run() 
        {
          //Do something here and return an integer,
          // for example **x**
        }

        public static void main(String args[]) throws Exception {
           // ...
           // I want to print out x value here.  
           // But as you can see, x disappears after thread finish its job.
        }
}


You would have to make x a field in the ServerStudentThread class, not a local variable. then add a method in the class like getValue() that returns x. From the main method, after you create the thread, run it, call the getValue() mehod on the class to print get the value of x and print it.


If you are using java 5 there is an Callable Interface.kindly look at this link http://java-x.blogspot.com/2006/11/java-5-concurrency-callable-and-future.html

// Code pasted from the link

public class CallableTester {

public static void main(String[] args) {
  Callable<Integer> callable = new CallableImpl(2);

  ExecutorService executor = new ScheduledThreadPoolExecutor(5);
  Future<Integer> future = executor.submit(callable);

  try {
      System.out.println("Future value: " + future.get());
  } catch (Exception e) {
      e.printStackTrace();
  }
}

}


public class CallableImpl implements Callable<Integer> {

private int myName;
CallableImpl(int i){
  myName = i;
}

public Integer call() {
  for(int i = 0; i < 10; i++) {
      System.out.println("Thread : " + getMyName() + " I is : " + i);
  }
  return new Integer(getMyName());

}

public int getMyName() {
  return myName;
}

public void setMyName(int myName) {
  this.myName = myName;
}

}


You should create thread (call Thread t = new ServerStudentThread(), then call t.start() then you should wait until the tread is done. For example call t.join().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜