Java multithreaded Programming

Source: Internet
Author: User
Tags stack trace thread class

Java provides built-in support for multithreaded programming. A multithreaded function contains two or more parts that can run concurrently. Each part of the program is called a thread, and each thread defines a separate execution path.
Multithreading is a special form of multitasking, but multithreading uses a much smaller resource overhead.
Here you define another term related to threading-process: a process that includes the memory space allocated by the operating system and contains one or more threads. A thread cannot exist independently, it must be part of a process. A process runs until all non-waiting threads end up running.
Multithreading can satisfy programmers to write high-efficiency programs to achieve the full use of CPU.
The life cycle of a thread
A thread is a process that executes dynamically, and it also has a process from generation to death.
Shows the full life cycle of a thread.

New status:
When a thread object is established using the New keyword and the thread class or its subclasses, the thread object is in the new state. It keeps this state until the program start () this thread.
Ready state:
When the thread object calls the start () method, the thread enters the ready state. The ready state thread is in the ready queue, waiting for the thread scheduler in the JVM to dispatch.
Running Status:
If the ready state thread gets the CPU resources, it can execute run (), at which point the thread is in the running state. A running thread is the most complex and can become a blocking state, a ready state, and a dead state.
Blocking Status:
If a thread executes a method such as sleep, suspend (hangs), and so on, the thread will enter a blocking state from the running state after the resource is lost. You can re-enter the ready state after the sleep time has arrived or the device resource has been acquired. Can be divided into three kinds:
Wait for blocking: the thread in the running state executes the wait () method, which causes the thread to enter a wait-blocking state.
Synchronous blocking: The thread acquires a synchronized synchronization lock failure (because the synchronization lock is occupied by another thread).
Other blocking: When an I/O request is made by the calling thread's sleep () or join (), the thread enters the blocking state. When the sleep () state times out, the join () waits for the thread to terminate or time out, or the I/O process completes and the thread is re-entered in a ready state.
Death Status:
When a running state thread finishes a task or other termination condition occurs, the thread switches to the terminating state.
Priority of the thread
Each Java thread has a priority, which helps the operating system determine the order in which the threads are dispatched.
The priority of a Java thread is an integer whose value range is 1 (thread.min_priority)-Ten (thread.max_priority).
By default, each thread will be assigned a priority of norm_priority (5).
Shares with Beijing higher priority threads are more important to programs, and processor resources should be allocated before low-priority threads. However, thread precedence does not guarantee the order in which threads are executed, and is very dependent on the platform.
Create a thread
Java provides three ways to create threads:
By implementing the Runnable interface;
By inheriting the Thread class itself;
Create threads from callable and future.
To create a thread by implementing the Runnable interface
The simplest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class simply executes a method call to run (), declared as follows:
public void Run ()
You can override this method, it is important to understand that run () can call other methods, use other classes, and declare variables, just like the main thread.
After you have created a class that implements the Runnable interface, you can instantiate a thread object in the class.
Thread defines several construction methods, and this is what we often use:
Thread (Runnable threadob,string threadname);
Here, Threadob is an instance of the class that implements the Runnable interface, and ThreadName specifies the name of the new thread.
After the new thread is created, you call it's start () method before it runs.
void Start ();
Here is an instance of creating a thread and starting to make it execute:
Instance
Class Runnabledemo implements Runnable {
Private Thread t;
Private String ThreadName;

Runnabledemo (String name) {
ThreadName = name;
System.out.println ("Creating" + threadname);
}

public void Run () {
System.out.println ("Running" + threadname);
try {
for (int i = 4; i > 0; i--) {
System.out.println ("Thread:" + ThreadName + "," + i);
Let the thread sleep for a while
Thread.Sleep (50);
}
}catch (Interruptedexception e) {
System.bjrongjinhuiyin.com.out.println ("Thread" + ThreadName + "interrupted.");
}
System.out.println ("Thread" + ThreadName + "exiting.");
}

public void Start () {
System.out.println ("starting" + threadname);
if (t = = null) {
t = new Thread (this, threadname);
T.start ();
}
}
}

public class Testthread {

public static void Main (String args[]) {
Runnabledemo R1 = new Runnabledemo ("Thread-1");
R1.start ();

Runnabledemo R2 = new Runnabledemo ("Thread-2");
R2.start ();
}
}

Compile the above program to run the following results:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread:thread-1, 4
Running Thread-2
Thread:thread-2, 4
Thread:thread-1, 3
Thread:thread-2, 3
Thread:thread-1, 2
Thread:thread-2, 2
Thread:thread-1, 1
Thread:thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
To create a thread by inheriting thread
The second way to create a thread is to create a new class that inherits the thread class and then creates an instance of the class.
The inheriting class must override the run () method, which is the entry point for the new thread. It must also call the start () method to execute.
The method of melting gold and silver is listed as a multi-threaded implementation, but it is an example of implementing the Runnable interface in essence.
Instance
Class Threaddemo extends Thread {
Private Thread t;
Private String ThreadName;

Threaddemo (String name) {
ThreadName = name;
System.out.println ("Creating" + threadname);
}

public void Run () {
System.out.println ("Running" + threadname);
try {
for (int i = 4; i > 0; i--) {
System.out.println ("Thread:" + ThreadName + "," + i);
Let the thread sleep for a while
Thread.Sleep (50);
}
}catch (Interruptedexception e) {
System.out.println ("Thread" + ThreadName + "interrupted.");
}
System.out.println ("Thread" + ThreadName + "exiting.");
}

public void Start () {
System.out.println ("starting" + threadname);
if (t = = null) {
t = new Thread (this, threadname);
T.start ();
}
}
}

public class Testthread {

public static void Main (String args[]) {
Threaddemo T1 = new Threaddemo ("Thread-1");
T1.start ();

Threaddemo T2 = new Threaddemo ("Thread-2");
T2.start ();
}
}

Compile the above program to run the following results:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread:thread-1, 4
Running Thread-2
Thread:thread-2, 4
Thread:thread-1, 3
Thread:thread-2, 3
Thread:thread-1, 2
Thread:thread-2, 2
Thread:thread-1, 1
Thread:thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Thread method
The following table lists some important methods of the thread class:
Ordinal method Description
1public void Start ()
Causes the thread to start executing, and the Java virtual machine calls the thread's Run method.
2public 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.
3public final void SetName (String name)
Change the thread name so that it is the same as the parameter name.
4public final void setpriority (int priority)
The priority of the thread to be rerouted.
5public final void Setdaemon (Boolean on)
Mark the thread as either a daemon thread or a user thread.
6public final void Join (long millisec)
The maximum time to wait for the thread to terminate is Millis milliseconds.
7public void Interrupt ()
The thread is disconnected.
8public Final Boolean isAlive ()
Tests whether the thread is active.
Tests whether the thread is active. The above method is called by the thread object. The following method is a static method of the thread class.
Ordinal method Description
1public static void Yield ()
Pauses the currently executing thread object and executes other threads.
2public static void sleep (long millisec)
Lets the currently executing thread hibernate (suspends execution) within the specified number of milliseconds, which is affected by the accuracy and accuracy of the system timer and scheduler.
3public Static Boolean Holdslock (Object x)
Returns true if and only if the monitor lock is persisted on the specified object by the front thread.
4public static Thread CurrentThread ()
Returns a reference to the currently executing thread object.
5public static void DumpStack ()
Prints the stack trace of the current thread to the standard error stream.
Instance
The following Threadclassdemo program demonstrates some of the methods of the thread class:
Displaymessage.java File Code:
File name: Displaymessage.java
Creating a thread by implementing the Runnable interface
public class DisplayMessage implements Runnable {
Private String message;

Public DisplayMessage (String message) {
this.message = message;
}

public void Run () {
while (true) {
SYSTEM.OUT.PRINTLN (message);
}
}
}

Guessanumber.java File Code:
File name: Guessanumber.java
Create a thread by inheriting the thread class

public class Guessanumber extends Thread {
private int number;
public Guessanumber (int number) {
This.number = number;
}

public void Run () {
int counter = 0;
int guess = 0;
do {
guess = (int) (Math.random () * 100 + 1);
System.out.println (This.getname () + "guesses" + guess);
counter++;
} while (guess! = number);
SYSTEM.OUT.PRINTLN ("* * correct!" + this.getname () + "in" + Counter + "guesses.**");
}
}

Threadclassdemo.java File Code:
File name: Threadclassdemo.java
public class Threadclassdemo {

public static void Main (String [] args) {
Runnable Hello = new DisplayMessage ("Hello");
Thread thread1 = new Thread (hello);
Thread1.setdaemon (TRUE);
Thread1.setname ("Hello");
System.out.println ("Starting Hello thread ...");
Thread1.start ();

Runnable bye = new DisplayMessage ("Goodbye");
Thread thread2 = new Thread (bye);
Thread2.setpriority (thread.min_priority);
Thread2.setdaemon (TRUE);
System.out.println ("Starting Goodbye thread ...");
Thread2.start ();

System.out.println ("Starting thread3 ...");
Thread thread3 = new Guessanumber (27);
Thread3.start ();
try {
Thread3.join ();
}catch (Interruptedexception e) {
System.out.println ("Thread interrupted.");
}
System.out.println ("Starting thread4 ...");
Thread thread4 = new Guessanumber (75);

Thread4.start ();
System.out.println ("Main () is ending ...");
}
}

The results of the operation are as follows, and the results are different for each run.
Starting Hello thread ...
Starting Goodbye thread ...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
Creating threads from callable and future
1. Create an implementation class for the callable interface and implement the call () method, which will act as the thread execution body and have a return value.
2. Create an instance of the callable implementation class, using the Futuretask class to wrap the callable object, which encapsulates the return value of the call () method of the Callable object.
3. Use the Futuretask object as the target of the thread object to create and start a new thread.
4. Call the Get () method of the Futuretask object to get the return value after the child thread execution ends.
Instance
public class Callablethreadtest implements callable<integer> {
public static void Main (string[] args)
{
Callablethreadtest CTT = new Callablethreadtest ();
futuretask<integer> ft = new futuretask<> (CTT);
for (int i = 0;i < 100;i++)
{
System.out.println (Thread.CurrentThread (). GetName () + "The value of the cyclic variable i" +i);
if (i==20)
{
New Thread (FT, "thread with return value"). Start ();
}
}
Try
{
System.out.println ("The return value of the child thread:" +ft.get ());
} catch (Interruptedexception e)
{
E.printstacktrace ();
} catch (Executionexception e)
{
E.printstacktrace ();
}

}
@Override
Public Integer Call () throws Exception
{
int i = 0;
for (; i<100;i++)
{
System.out.println (Thread.CurrentThread (). GetName () + "" +i);
}
return i;
}
}

Java multithreaded Programming

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.