Java threads and java threads

Source: Internet
Author: User
Tags date1

Java threads and java threads

1 inherit thread

public class MultiThread1 extends Thread{public void run(){for(int i=0; i<7; i++){System.out.println("name:"+this.getName()+" i:"+ i+"   ");}}public static void main(String[] args) {MultiThread1 tA = new MultiThread1();tA.setName("AA");MultiThread1 tB = new MultiThread1();tB.setName("BB");tA.start();tB.start();}}


2. Runnable

public class MyRunnable implements Runnable{private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic void run() {// TODO Auto-generated method stubfor(int i=0; i<10; i++){System.out.println("name:"+this.getName()+" i:"+ i+"   ");}}public static void main(String[] args) {MyRunnable mA = new MyRunnable();mA.setName("AA");MyRunnable mB = new MyRunnable();mB.setName("BB");Thread t1 = new Thread(mA);Thread t2 = new Thread(mB);t1.start();t2.start();}}

 

3. ExecutorService, Callable, and Future are used to implement multithreading with returned results
ExecutorService, Callable, and Future objects are actually functional classes in the Executor framework. To learn more about the Executor framework, visit the http://www.javaeye.com/topic/366591, which is explained in detail here. The thread that returns the result is a new feature introduced in JDK1.5, which is indeed very practical. With this feature, I don't need to take a long time to get the returned value, and even if it is implemented, it may be exposed.
The Callable interface must be implemented for a task that can return values. Similarly, a task without a return value must be a Runnable interface. After executing the Callable task, you can get a Future Object. On this Object, you can call get to get the Object returned by the Callable task, combined with the thread pool interface ExecutorService, You can implement multiple threads with returned results. The following provides a complete multi-threaded test example with returned results. It can be directly used if it has been verified in JDK.

 

Import java. util. concurrent. *; import java. util. date; import java. util. list; import java. util. arrayList;/*** threads with returned values */@ SuppressWarnings ("unchecked") public class Test {public static void main (String [] args) throws ExecutionException, 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 task lists with returned values <Future> List = new ArrayList <Future> (); for (int I = 0; I <taskSize; I ++) {Callable c = new MyCallable (I + ""); // execute the task and obtain the Future object Future f = pool. submit (c); // System. out. println (">>>" + f. get (). toString (); list. add (f);} // close the thread pool. shutdown (); // obtain the running result of all concurrent tasks for (Future f: list) {// obtain the return value of the task from the Future object and output it to the console System. out. println (">>>" + f. get (). toString ();} Date date2 = new Date (); System. out. println ("---- program stops running ----, program running time [" + (date2.getTime ()-date1.getTime () + "millisecond ]");}} 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 + ""); return taskNum + "The task returns the running result. The current task time is [" + time + "millisecond ]";}}

 

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.