Java Multithreading (i) Overview and creation

Source: Internet
Author: User

Multithreading is one of the features of the Java language that enables programs to have multiple execution fragments at the same time, synchronizing or working asynchronously based on different conditions and environments. Threads are similar to process implementations, but their service objects are different, processes represent a program running in the operating system platform, and a program will contain multiple threads.

 Process:

  Usually the running program becomes a process, and now the computer basically supports multi-process operations, such as the use of computers can be Internet access, listening to music, but there is only one CPU on the computer, in fact, can not run these processes simultaneously, the CPU is actually using different time fragments to alternately execute each process, Because the conversion is fast, it feels like it's running at the same time.

  Thread:

  Multiple tasks can also be performed within a process, which can be called a thread within a process, a thread being an entity in a process, and a process can have multiple threads.

A thread must have a parent process, and the system does not allocate resources for the thread, and it shares system resources for that process with other threads in the process. If multiple threads in a process share the same memory address space, this means that these threads can access the same variables and objects, which makes it easier to share information between threads.

  Creation of Threads:

  In the Java language, a thread is also an object, but not any object can be a thread, only an object that implements the Runnable interface or inherits the thread class can become a thread. Here are two ways to create a thread:

(i) Inherit the thread class

1. Common methods:

Common methods in the thread class include Start (), Interrupt (), join (), run () method, and so on. where the start () and run () methods are most commonly used, the start () method starts the thread, and the Run () method is the thread's topic method, and the reader can override the run () method as needed.

2. Construction Method:

 PublicThread ();//default construction method, no parameter PublicThread (Runnable target);//Based on the construction method of Runable object, the business logic of the thread is handed to the Runnable object passed by the parameter to implement PublicThread (threadgroup Group, Runnable target),//threadgroup class represents a set of threads, based on Runnable object and thread grouping object construction method PublicThread (String name);//The constructor that specifies the thread name, which is the name of the newly created thread object PublicThread (threadgroup Group, String name);//Specify Thread group and thread name Publicthread (Runnable target, String name);//construction method based on Runnable object and specifying thread name PublicThread (threadgroup Group, Runnable Target, String name);//Specify Thread group, name, and Runnable object PublicThread (threadgroup group, Runnable Target, String name,LongstackSize);//Specify thread grouping, name, Runnable object, and stack size

3. Example:

To implement threading functionality in the Java language, you can inherit the Java.lang.Thread class, which already has all the necessary schemas for creating and running threads, by covering the run () method in the thread class to implement the functionality required by the user, instantiating the custom thread class, Start the thread using the start () method.

/*** Inherit the thread class to create a Simplethread thread class that will create two threads <br> * output information at the same time on the console, thus enabling cross-display of two task output information*/ Public classSimplethreadextendsThread {//constructor method, parameter is thread name     PublicSimplethread (String name) {setName (name); }    //override the Run () method     Public voidrun () {inti = 0;  while(I++ < 5) {            Try{System.out.println ( This. GetName () + "perform step" +i); Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }     Public Static voidMain (string[] args) {simplethread thread1=NewSimplethread ("Thread 1"); Simplethread thread2=NewSimplethread ("Thread 2");        Thread1.start ();    Thread2.start (); }}

Execution results

(ii) Realization of the Runnable interface

The class that implements the Runnable interface can become a thread, and the thread class is capable of threading because it implements the Runnable interface. The runnable interface has only one method that is the run () method, and the run () method must be covered after implementing the Runnable interface.

 Public class Implements Runnable {}
Public Interface Runnable { Public Abstract void run ();}

Essentially, runnable is an interface in the Java language to implement threads, and any class that implements threading functionality must implement this interface. Because the thread class implements the interface, the class that inherits the thread has the appropriate threading capability.

Although you can implement threads in a way that inherits the thread class, because in the Java language, you can inherit only one class, and if a user-defined class has inherited another class, you cannot inherit the thread class, and you cannot use threads. The Java language provides the user with the Java.lang.Runnable interface, which implements this interface and inherits the thread class with the same effect when instantiating a thread object, you can pass in an object that implements the Runnable interface as a parameter, and the thread class calls the Runnable object's Run () method, and then executes the contents of the run () method.

Instance:

/*** Create the Simplerunnable class, which implements the Runnable interface, and in the Run () method <br> * Each interval of 0.5 seconds, output a "*" character in the console until 15 "*" characters are output. */ Public classSimplerunnableImplementsRunnable {//overwrite the Run () method     Public voidrun () {inti = 15;  while(i-->= 1) {            Try{System.out.print ("*"); Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }     Public Static voidMain (string[] args) {Thread thread1=NewThread (NewSimplerunnable (), "Thread 1");    Thread1.start (); }}

Execution results

The content of this article is more reference to book knowledge, essays written down to learn to share and easy to view later.

Java Multithreading (i) Overview and creation

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.