Get the results of an operation from a Java thread

Source: Internet
Author: User
Tags thread class

If you have any comments, criticisms or praise: please send me a letter climber_2002@sina.com

Java threads are implemented by thread, generally we create threads to do a complex operation, and then in the main thread of the operation of the results of processing, but the thread of the run function does not return the value, then we calculate the results, how to notify the other threads, This article describes several ways to return information.

One. Creation of Java Threads

There are two ways to create a thread, one is to inherit the thread class, the other is to implement Runnable, and then pass it to a thread's constructor, as follows (suppose we want to compute 1 to 10000 in a thread):

1. Inherit thread:

public class AddThread extends Thread {
public void run() {
  int result = 0;
  for(int i = 1; i <= 10000; i++) {
  result += i;
  }
}
}

Run Addthread:

Addthread thread = new Addthread ();

Thread.Start ();

2. Implement Interface runnable:

public class Add implements Runnable {
public void run() {
  int result = 0;
  for(int i = 1; i <= 10000; i++) {
  result += i;
  }
}
}

Run this thread: thread thread = new Thread (new Add ());

Thread.Start ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.