Original Java multithreading (i)

Source: Internet
Author: User

It is impossible to read a book without practice. To practice the ~~~~~~ (quote please specify source)

First look at the encyclopedia of the introduction of multithreading

Http://baike.baidu.com/view/65706.htm?fr=aladdin

Java Support for multithreading

Java 3 common ways to create multithreading:

1) inherit the thread class

Rewrite the thread class's Run method, create the thread subclass instance, and start the threads.

For example:

/* * @author [email protected]  Wangxu */public class Treadofextends extends thread{private int i;//rewrite run () method public Voi D run () {for (i=0; i<50; i++) {System.out.println (GetName () + "" + i),////inherit the thread class directly using this to get the current thread}}public static void M Ain (string[] args) {System.out.println (Thread.CurrentThread (). GetName ()); for (int i=0; i<50; i++) {if (i = = 10) {// The start () method is called directly by creating a class object to new Treadofextends (). Start (); New Treadofextends (). Start ();}}}


2) Implement Runnable interface

Rewrite the run () method to create the runnable instance as the target of the thread.

For example:

public class Threadofrun implements Runnable {private int i;//implement the Run () method in the Runnable interface public void Run () {for (i=0; i<50; i+ +) {System.out.println (Thread.CurrentThread (). GetName () + "" + i);//The  current process cannot be obtained through the This keyword by implementing the interface to implement multithreading}}public static void Main (string[] args) {for (int i=0; i<50; i++) {System.out.println (Thread.CurrentThread (). GetName () + "" + I if (i = =) {   Threadofrun tor = new Threadofrun ();   The new thread   (Tor, "Thread 1") will need to be constructed by using thread's constructor method. Start ();   New Thread (Tor, "Thread 2"). Start ();}}}    


3) Java 5 can be used more powerful means-to implement the callable interface

Create and start a new thread using the target of the Futuretask object as the thread object

Import Java.util.concurrent.callable;import Java.util.concurrent.futuretask;public class Threadofcallble implements callable<integer> {                                        //support generic public    integer call () throws Exception {    int i;    for (i=0; i<50; i++) {    System.out.println (Thread.CurrentThread (). GetName () + "" + i);    } Return i;//has return value}public static void Main (string[] args) {//Create callable object threadofcallble TOC = new threadofcallble ();// Wrapping callable objects through futuretask futuretask<integer> ft = new futuretask<integer> (TOC); for (int i=0; i<50; i++) {if (i ==10) {new Thread (ft, "Newthread"). Start ();}} try {//Gets the return value of the new thread System.out.println ("The return value of the child thread:" + ft.get ());} catch (Exception e) {e.printstacktrace ();}}}


Three ways of comparison: the latter two methods are very suitable for multiple same threads to handle the same resource situation, the CPU, code and data can be separated, more consistent with the object-oriented thinking, but also can inherit other classes, so generally adopt the latter two methods.

Thread life cycle: New and ready state--run and block state--thread dead (non-resurrected).

Join thread

When a join method of another thread is called in a program execution, the thread is blocked until the join thread finishes execution.

<pre class= "java" name= "code" >public class Threadofjoin extends Thread {public threadofjoin (String name) {Super ( name);}    public void Run () {for (int i=0; i<50; i++) {System.out.println (GetName ());}} public static void Main (string[] args) {new Threadofjoin ("Newthread"). Start (), for (int i=0; i<50; i++) {if (i = =) {THR Eadofjoin Toj = new Threadofjoin ("Joinedthread"); Toj.start (); try {toj.join ();//The main thread calls the Toj join method and needs to wait for Toj to execute after the main thread is executed} catch (Interruptedexception e) {e.printstacktrace ();}} System.out.println (Thread.CurrentThread (). GetName ());}}}

To be continued: Thread priority, thread synchronization, mutex, Sync lock, deadlock, thread communication.

Comment area leave an email to get "Java multithreaded design mode" PDF version (through the web crawler applet auto-match crawl your email and automatically sent to you)

Original Java multithreaded Walkthrough (i)

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.