Java thread-related knowledge point summary __java

Source: Internet
Author: User

Java Threads: Concepts and Principles

1, the operating system thread and the concept of the process


The operating system is now a multitasking operating system. Multithreading is a way to achieve multitasking. A process is a running application in memory in which each process has its own separate piece of memory space, and multiple threads can be started in a process. For example, in a Windows system, a running EXE is a process. A thread is an execution process in a process in which multiple threads can be run. For example, a java.exe process can run many threads. Threads always belong to a process, and multiple threads in the process share the memory of the process. "At the same time" execution is the feeling of the person, the thread actually rotates between the execution.


2. Threads in Java

In Java, a "thread" 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 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 created by the operating system or the user itself.


Java Threads: Creating and starting

A, defining threads

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.

b, Instantiating threads

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)

C, start 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

/**&NBSP
*  The class   that implements the Runnable interface;

*  @author  leizhimin 2008-9-13  18:12:10&NBSP
*/ 
public class dosomething implements runnable { 
private string name; 

public dosomething (string name)  { 
THIS.NAME = NAME;&NBSP


Public void 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
*/
public class Testrunnable {
public static void 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
*/
public class Testthread extends thread{
Public Testthread (String name) {
Super (name);
}

public void Run () {
for (int i = 0;i<5;i++) {
For (long k= 0; k <100000000;k++);
System.out.println (This.getname () + ":" +i);
}
}

public static void 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.

iii. Java Threads: Interaction

Thread interaction is a more complex issue, given a scenario in which code is written to properly use the wait, notify, and notify all threads.

First, the basics of threading interaction

Thread interaction knowledge points need to be learned from the three methods of the Java.lang.Object class:

void Notify ()
Wakes up a single thread waiting on this object monitor.
void Notifyall ()
Wakes up all threads waiting on this object monitor.
void Wait ()
Causes the current thread to wait until another thread calls the object's notify () method or the Notifyall () method.

Of course, wait () has two other overloaded methods:

void wait (long timeout)
Causes the current thread to wait until the other thread calls the object's notify () method or Notifyall () method, or exceeds the specified amount of time.
void Wait (long timeout, int nanos)
Causes the current thread to wait until another thread calls the object's notify () method or Notifyall () method, or another thread interrupts the current thread, or has exceeded a certain amount of actual time.

These methods are used to help the thread pass the time state that the thread is concerned about.

The key points to remember about waiting/notification are:

The Wait (), notify (), Notifyall () method must be invoked from within the synchronization environment. A thread cannot invoke a method of waiting or notifying on an object unless it has a lock on that object.

Wait (), notify (), Notifyall () are instance methods of object. Like each object has a lock, each object can have a list of threads that they wait for from that signal (notification). The thread obtains this waiting list by executing the Wait () method on the object. From that point on, it no longer executes any other directives until the Notify () method of the object is invoked. If multiple threads wait on the same object, only one thread is selected (not guaranteed in what order) to continue. If no threads are waiting, no special action is taken.

Here's an example to see:

/**&NBSP
*  Compute the data   the output of other thread locks;

*  @author  leizhimin 2008-9-15  13:20:38&NBSP
*/ 
public class threada { 
Public static void  main (String[] args)  { 
threadb b = new threadb ();  
// Start compute thread  
B.start ();
//Thread A owns the lock on the B object. In order to invoke the wait () or notify () method, the thread must be the owner of that object lock  
synchronized  (b)  { 
try { 
System.out.println ("Wait for object B to complete the calculation ...") ");  
//When line a waits for  
B.wait ();  
} catch  (interruptedexception e)  { &NBSP
E.printstacktrace ();  

System.out.println ("The sum calculated by the B object is:"  + b.total); 


}

/**
* Calculate 1+2+3 +100 and
*
* @author leizhimin 2008-9-15 13:20:49
*/
public class Threadb extends Thread {
int total;

public void Run () {
Synchronized (this) {
for (int i = 0; i < i++) {
Total = i;
}
(completed calculation) wakes a single thread waiting on this object monitor, in this case thread A is awakened
Notify ();
}
}
}

Wait for object B to complete the calculation ...
The sum of the B-object calculations is: 5050

Process finished with exit code 0

Please note:

When the Wait () method is invoked on an object, the thread that executes the code immediately discards its lock on the object. However, calling notify () does not mean that the thread will discard its locks. If the line Cheng Rongjian completes the synchronization code, the thread does not discard the lock until it is removed. Therefore, simply calling notify () does not mean that the lock becomes available at this time.

Two, multiple threads are waiting for an object lock to use Notifyall ()

In most cases, it is best to notify all threads waiting for an object. If you do this, you can use Notifyall () on the object to flush all threads waiting on this object out of the waiting area and return to the operational state.

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.