Dark Horse Programmer---Java Multi-threading usage

Source: Internet
Author: User

------- Android Training , Java training , look forward to communicating with you! ----------

Java threading

First, the concept of the operating system thread and process

The operating system now is a multitasking operating system. Multithreading is a way to achieve multitasking.

A process is an application running in memory in which each process has its own separate piece of memory, and a process can start multiple threads. For example, in a Windows system, a running EXE is a process.

A thread is an execution process in a process that can run multiple threads in a process. For example, a java.exe process can run many threads. Threads are always part of a process, and multiple threads in a process share the memory of the process. "At the same time" execution is a human feeling, which actually rotates between threads.

Second, threads in Java

In Java, "threading" refers to two different things:
1, an example of Java.lang.Thread class;

2, the execution of the thread.

Use the Java.lang.Thread class or the Java.lang.Runnable interface to write code to define, instantiate, and start new threads. A thread class instance is just an object that, like any other object in Java, has variables and methods that live and die on the heap. In Java, each thread has a call stack, and the thread runs in the background even if no new threads are created in the program. A Java application always runs from the main () method, and the Mian () method runs inside a thread, which is called the main thread. Once a new thread is created, a new call stack is generated.


Threads are divided into two categories: the user thread and the waiting thread. The JVM shuts down automatically when all user threads have finished executing. But the waiting thread is not independent of the JVM, and the waiting thread is typically created by the operating system or the user himself.

Java Threads: Creating and starting

One, define the thread

1, extended Java.lang.Thread class.

There is a run () method in this class, and you should be aware of its usage:

public void Run()

If the thread is constructed using a standalone runnable run object, the Run method of the Runnable object is called, otherwise the method does nothing and returns.


Subclasses of thread should override this method.

2, realize java.lang.Runnable interface.


void Run()

When you create a thread using an object that implements the interface runnable, starting the thread causes the Run method of the object to be called in the thread that executes independently.

The general contract for the method run is that it may perform any required operations.


Second, instantiate the thread


1, if the extension of the Java.lang.Thread class thread, then the direct new can.


2, if the implementation of the Java.lang.Runnable interface class, then use the thread construction method:

Thread (Runnable target)
Thread (Runnable target, String name)
Thread (threadgroup group, Runnable target)
Thread (threadgroup group, Runnable Target, String name)
Thread (threadgroup group, Runnable Target, String name, long stackSize)


Third, start the thread


Call the Start () method on the thread object of the thread, not run () or any other method.

Before the start () method is called: The thread is in the new state, the new state refers to a thread object, but there is no real thread.

After calling the start () method: A series of complex things happened

Start a new execution thread (with a new call stack);

The thread is transferred from the new state to the operational state;

When the thread obtains an opportunity to execute, its target run () method runs.

Note: For Java, the run () method has nothing special. Like the main () method, it is just a new thread that knows the method name (and signature) of the call. Therefore, it is legal to raise the Run method on runnable or thread. But does not start a new thread.


Iv. examples


1. Multithreading example of implementing Runnable interface

/**
* Classes that implement the Runnable interface
*
* @author leizhimin 2008-9-13 18:12:10
*/
Publicclass dosomethingimplements Runnable {
private String name;
Public dosomething (String name) {
THIS.name = name;
}

Publicvoid Run () {
for (int i = 0; i < 5; i++) {
for (long k = 0; k < 100000000; k++);
SYSTEM.OUT.PRINTLN (name + ":" + i);
}
}
}
/** 
* Testing multi-threaded threads implemented by the Runnable class
* @author leizhimin 2008-9-13 18:15:02
*/
Publicclass testrunnable {
Publicstaticvoid Main (string[] args) {
DoSomething DS1 = new DoSomething ("a three");
DoSomething ds2 = new DoSomething ("John Doe");
thread T1 = new Thread (DS1);
Thread t2 = new Thread (DS2);
T1.start ();
T2.start ();
}
}

Execution Result:
John Doe: 0
A three: 0
John Doe: 1
A three: 1
John Doe: 2
John Doe: 3
A three: 2
John Doe: 4
A three: 3
A three: 4

Process finished with exit code 0
2. Multithreading example of extending the thread class implementation
/** 
* Test extended thread class implementation of multi-threaded threads
* @author leizhimin 2008-9-13 18:22:13
*/
Publicclass Testthreadextends thread{
Public Testthread (String name) {
Super (name);
}
Publicvoid Run () {
for (int i = 0;i<5;i++) {
For (long k= 0; k <100000000;k++);
System.out.println (This.getname () + ":" +i);
}
}
Publicstaticvoid Main (string[] args) {
Thread T1 = new Testthread ("a three");
Thread t2 = new Testthread ("John Doe");
T1.start ();
T2.start ();
}
}

Execution Result:
A three: 0
John Doe: 0
A three: 1
John Doe: 1
A three: 2
John Doe: 2
A three: 3
A three: 4
John Doe: 3
John Doe: 4
Process finished with exit code 0

For the above multithreaded program code, the result of the output is indeterminate. One of the statements for (long k= 0; k <100000000;k++) is used to simulate a very time-consuming operation.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Dark Horse Programmer---Java Multi-threading usage

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.