Detailed three Java ways to implement multithreading _java

Source: Internet
Author: User
Tags date1 thread class

There are two ways to implement multithreading in Java: Inherit the thread class and implement the Runnable interface .

1. Inherit the thread class, overriding the parent class run () method

 public class Thread1 extends Thread {public
 
    void run () {for
        (int i = 0; i < 10000; i++) {
            System.out.prin TLN ("I am a Thread" +this.getid ())
        ;
    }
 
    public static void Main (string[] args) {
        thread1 Th1 = new Thread1 ();
        Thread1 Th2 = new Thread1 ();
        Th1.run ();
        Th2.run ();
    }
   

The run () method is just a normal method, which is sequential, that is, Th1.run () execution completes before Th2.run () is executed, so that only one main thread is written. Multithreading loses its meaning, so you should start the thread with the start () method, and the start () method will automatically call the run () method. The preceding code should read:

 public class Thread1 extends Thread {public
     
    void run () {for
        (int i = 0; i < 10000; i++) {
            System.out.prin TLN ("I am a Thread" +this.getid ())
        ;
    }
 
    public static void Main (string[] args) {
        thread1 Th1 = new Thread1 ();
        Thread1 Th2 = new Thread1 ();
        Th1.start ();
        Th2.start ();
    }

Start a new thread through the start () method. This way, regardless of whether the run () method of the Th1.start () is executed, continue to execute Th2.start () if the following code does not have to wait for Th2.start () execution to complete. (The output thread ID is an irregular alternating output)

2. Implement Runnable interface

public class Thread2 implements Runnable {public
 
    String threadname;
     
    Public thread2 (String tname) {
        threadname = tname;
    }
     
     
    public void Run () {for
        (int i = 0; i < 10000; i++) {
            System.out.println (threadname);
        }
    }
     
    public static void Main (string[] args) {
        thread2 Th1 = new Thread2 ("Thread A");
        Thread2 Th2 = new Thread2 ("Thread B");
        Th1.run ();
        Th2.run ();
    }



Like the thread Run method runnable Run is just a normal method, in the Main method Th2.run () must wait for Th1.run () execution completed before execution, the program uses only one thread. For multithreading purposes, you also pass the thread's start (note: runnable is not the Start method). The above code is modified to:

public class Thread2 implements Runnable {public
 
    String threadname;
     
    Public thread2 (String tname) {
        threadname = tname;
    }
     
     
    public void Run () {for
        (int i = 0; i < 10000; i++) {
            System.out.println (threadname);
        }
    }
     
    public static void Main (string[] args) {
        thread2 Th1 = new Thread2 ("Thread A");
        Thread2 Th2 = new Thread2 ("Thread-b");
        Thread myth1 = new Thread (TH1);
        Thread myth2 = new Thread (TH2);
        Myth1.start ();
        Myth2.start ();
    }



3. Use Executorservice, callable, future to implement multithreading with return results (JDK5.0 later)
a task that can return a value must implement the callable interface, and similarly, a task with no return value must runnable the interface. After performing the callable task, you can get a future object that invokes get on the object to obtain the object returned by the callable task, and then combine the thread pool interface Executorservice to achieve the legendary return of the results of multithreading. The following provides a complete example of a multithreaded test with return results, which can be used directly under JDK1.5. The code is as follows:

Import java.util.concurrent.*; 
Import Java.util.Date; 
Import java.util.List; 
  
Import java.util.ArrayList; /** * Thread with return value/@SuppressWarnings ("Unchecked") public class Test {public static void main (string[] args) throws Exe 
  Cutionexception, interruptedexception {System.out.println ("----program starts running----"); 
  
  Date date1 = new Date (); 
  int tasksize = 5; 
  Create a thread pool executorservice pool = Executors.newfixedthreadpool (tasksize); 
  Create multiple tasks with return values list<future> List = new arraylist<future> (); 
  for (int i = 0; i < tasksize i++) {callable c = new Mycallable (i + ""); 
  Perform the task and get the Future object Future f = pool.submit (c); 
  System.out.println (">>>" + f.get (). toString ()); 
  List.add (f); 
  
  ///Close thread pool Pool.shutdown (); Gets the run result for all concurrent tasks for (Future f:list) {//Gets the return value of the task from the Future object and outputs it to the console System.out.println (">>>" + f.get ( 
  ). ToString ()); 
  Date Date2 = new Date (); SYSTEM.OUT.PRINTLN ("----program finishes running----, programRun Time "" + (Date2.gettime ()-date1.gettime ()) + "milliseconds"); 
  
} class Mycallable implements callable<object> {private String tasknum; 
Mycallable (String tasknum) {this.tasknum = Tasknum; 
  Public Object Call () throws Exception {System.out.println (">>>" + tasknum + "task start"); 
  Date DATETMP1 = new Date (); 
  Thread.Sleep (1000); 
  Date DATETMP2 = new Date (); 
  Long time = Datetmp2.gettime ()-datetmp1.gettime (); 
  System.out.println (">>>" + Tasknum + "mission terminated"); 
return tasknum + "The task returns the running result, the current task time" "+ Times +" milliseconds "";
 } 
}

Code Description:
The executors class in the above code provides a series of factory methods for the first thread pool, and the returned thread pool implements the Executorservice interface.
public static Executorservice newfixedthreadpool (int nthreads)
Creates a thread pool of fixed number of threads.
public static Executorservice Newcachedthreadpool ()
Creates a cacheable thread pool, and calling execute reuses the previously constructed thread (if the thread is available). If an existing thread is not available, create a new thread and add it to the pool. Terminates and removes threads from the cache that have not been used for 60 seconds.
public static Executorservice Newsinglethreadexecutor ()
Create a single-threaded executor.
public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize)
Create a thread pool that supports timed and periodic task execution, which in most cases can be used instead of the timer class.
Executoreservice provides a submit () method that passes a callable, or runnable, back to future. If the executor background thread pool has not completed the callable calculation, this call returns the Get () method of the future object, blocking until the calculation is complete.

Summary: 2 ways to implement Java multithreading, Runable is an interface, thread is a class, runnable only provides a run method, it is recommended to use Runable to implement Java multithreading, in any case, ultimately need to pass Thread.Start () To enable the thread to be in a running state. The third way is to listen to the brothers in the group introduced, so Baidu to fill up.

The above is the entire content of this article, I hope to help you learn.

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.