Java Early Learning-thread description __java

Source: Internet
Author: User

Use the Java.lang.Thread class or the Java.lang.Runnable interface to write code to define, instantiate, and start a new thread.

An instance of a thread class is just an object, like any other object in Java, with 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 is always run from the main () method, and the Mian () method runs within a thread, which is called the master thread.

Once a new thread is created, a new call stack is generated.

Threads are divided into two categories: User threads and waiting threads.


When all user threads have finished executing, the JVM shuts down automatically. But the waiting thread is not independent of the JVM, and the waiting thread is typically a Java thread created by the operating system or the user itself : Creating and starting

first, define the thread

1, extend the Java.lang.Thread class.

There is a run () method in this class that should be noted for its usage:

public void Run()

If the thread is constructed using a stand-alone 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 with an object that implements the interface runnable, starting the thread will cause the object's Run method to be called in a thread that executes independently.

The general contract for method Run is that it may perform any desired action.

second, the instantiation of the thread

1, if it is extended Java.lang.Thread class thread, then direct new can.

2. If it is a class that implements the Java.lang.Runnable interface, then the thread construction method is used:

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 thread objects on threads, not run () or any other method.

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

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

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

The thread is transferred from a new state to a running state;

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

Note: There is nothing special about the run () method for Java. Like the main () method, it is just the method name (and signature) that the new thread knows the call. Therefore, it is legal to use the Run method on runnable or thread increase. It does not start a new thread.

Iv. Examples

1, realize the Runnable interface Multithreading example

/**
* The class that implements 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);
}
}
}

/**
* Test multithreaded routines implemented by Runnable class
*
* @author leizhimin 2008-9-13 18:15:02
*/
Publicclass testrunnable {
Publicstaticvoid Main (string[] args) {
DoSomething DS1 = new DoSomething ("Ah San");
DoSomething ds2 = new DoSomething ("Dick");

thread T1 = new Thread (DS1);
Thread t2 = new Thread (DS2);

T1.start ();
T2.start ();
}
}

Execution results:

Dick: 0
A third: 0
Dick: 1
A third: 1
Dick: 2
Dick: 3
A third: 2
Dick: 4
A third: 3
A third: 4

Process finished with exit code 0

2, extended thread class implementation of multithreaded examples

/**
* Test multithreaded routines implemented by the extended thread class
*
* @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 ("Ah San");
Thread t2 = new Testthread ("Dick");
T1.start ();
T2.start ();
}
}

Execution results:

A third: 0
Dick: 0
A third: 1
Dick: 1
A third: 2
Dick: 2
A third: 3
A third: 4
Dick: 3
Dick: 4

Process finished with exit code 0

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

v. Some common problems

1, the name of the thread, a running thread always has a name, the name has two sources, one is the virtual machine to give their own name, one is your own set name. Without specifying the thread name, the virtual machine always assigns a name to the thread, and the main thread's name is always Mian, and the name of the non main thread is indeterminate.

2, the thread can set the name, also can get the name of the thread, even the main thread is no exception.

3, get the current thread of the object method is: Thread.CurrentThread ();

4, in the above code, can only guarantee that each thread will start, each thread will run until completed. A series of threads that start in some order does not mean that they will be executed in that order. For any set of threads to start, the scheduler does not guarantee its execution order and duration is not guaranteed.

5, the thread completes when the thread target run () method ends.

6. Once the thread is started, it can never be restarted again. Only one new thread can be started, and only once. Either a running thread or a dead thread can be restarted.

7, the thread scheduling is part of the JVM, on a CPU machine, in fact, can only run one thread at a time. Only one thread stack executes at a time. The JVM thread scheduler determines which thread is actually running which is in the running state.

One of the many running threads will be selected as the current thread. The order in which a running thread is selected to run is not guaranteed.

8. Although the queue format is usually used, it is not guaranteed. The form of a queue is when a thread completes the "round", it moves to the end of the running queue and waits until it finally queues to the front of the queue before it is checked again. In fact, we call it a runtime pool, not a running queue, to help understand the fact that threads are not all in a guaranteed order to sing a queue.

9, although we do not have the inability to control the thread scheduler, but there are other ways to affect the way the thread scheduling. Java Threads: Line stacks model and thread variables

To understand the principle of thread scheduling and the thread execution process, you must understand the line stacks model.

A line stacks is a stack of memory thread scheduling at some point in time, and the method currently invoked is always on top of the stack. The content of the line stacks is dynamically changing as the program runs, so the research thread stack must choose a runtime (actually where the code runs).

The following is a sample code explaining the process of a thread (call) stack change.

This picture depicts the virtual machine thread calling the stack sketch when the code executes to two different times 1 or 2.

When the program executes to T.start (), the program has one more branch (add a call stack B), so stack A, stack b executes in parallel.

From here you can see the difference between the method invocation and the thread initiation. Java Threads: Transition of thread State

One, thread state

The state transitions of threads are the basis of thread control. The total thread state can be divided into five states: Live, die, run, run, wait/block, respectively. Use a diagram to describe the following:

1, new state: The thread object has been created and no start () method has been invoked on it.

2. Operational status: When the thread is eligible to run, but the scheduler has not yet selected it as the state of the thread when it is running. When the start () method is invoked, the thread first enters the operational state. After a thread has run or comes back from a blocking, waiting, or sleeping state, it is also returned to the operational state.

3. Running state: The state in which the thread scheduler selects a thread as the current thread from the runtime pool. This is the only way in which a thread enters a running state.

4. Wait/block/Sleep status: This is the state in which the thread is eligible to run. In fact, this three-state combination is one of the common things: threads are still alive, but currently there is no condition to run. In other words, it is operational, but if an event occurs, he may return to a running state.

5. Death state: When the thread's run () method is finished, it is considered dead. This thread object may be alive, but it is no longer a separate thread to execute. Once a thread dies, it cannot be resurrected. If the start () method is invoked on a dead thread, a Java.lang.IllegalThreadStateException exception is thrown.

For detailed state transition diagrams, see my diagram in the Java Multithreaded programming summary

Second, prevent thread execution

For thread blocking, consider three areas, regardless of Io blocking:

Sleep

Waiting

Blocked because a lock on an object is required.

1, Sleep

Thread.Sleep (Long Millis) and Thread.Sleep (long millis, int Nanos) static methods force the currently executing thread to hibernate (suspend execution) to "slow down the thread." When a thread sleeps, it sleeps somewhere and does not return to the operational state until it wakes up. When the sleep time expires, it is returned to the operational state.

Reason for thread sleep: The thread executes too fast or needs to be forced into the next round because the Java specification does not guarantee a reasonable rotation.

Implementation of sleep: calling a static method.

try {
Thread.Sleep (123);
catch (Interruptedexception e) {
E.printstacktrace ();
}

Sleep location: In order for other threads to have a chance to execute, the call to Thread.Sleep () can be put into thread run (). This will make it possible for the thread to sleep during execution.

For example, in the previous example, a time-consuming operation was changed to sleep to slow down the execution of the thread. You can write this:

public void Run () {
for (int i = 0;i<5;i++) {

//  a time-consuming operation to slow down the execution of a thread
//            for (long k= 0 ; K <100000000;k++);
            try {
                 thread.sleep (3);
           } catch (Interruptedexception e) {
                 e.printstacktrace ();  .
           }

            System.out.println (this.getname () + ":" +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.