Java Thread Programming-two thread programs

Source: Internet
Author: User

Java built-in thread support

The good thing about Java is that it supports built-in write multithreading. Java designers know the value of multi-threaded programming, so they decide to directly support threads in the core part of Java. In Chapter 7th, "concurrent access objects and variables" describes how the synchronized keyword in Java is used to lock objects and classes to control concurrent access to data. The thread and threadgroup classes are in the core APIs of the Java. lang package. With the support of the wait () notify () method, the parent class objects of all classes in Java have the ability to communicate between threads. Even if the current operating system does not support the thread concept, a well-written JVM can simulate a multi-threaded environment. In Java, thread support is not post-approval, but included in the design from the very beginning.

Chapter 2: a simple example of two threads
Overview

This chapter shows how simple it is to create and run a thread in a small Java application. The first thread is always in the "Main" thread created by JVM, which starts to run the program. The main thread then creates the second thread. Each thread prints its own information on the console to prove that they seem to run in synchronous mode.

To create a thread, follow these steps:

  • Inherit from Java. Lang. Thread class
  • Override the run () method in the subclass that inherits the thread;
  • Create an instance of this new class
  • Call the START () method of the instance.

Inherit from Java. Lang. Thread class

In JVM, each thread is associated with an instance of the Java. Lang. Thread class. These thread objects act as interfaces for interaction with underlying operating system threads. You can start, stop, interrupt, name, set the priority, and query the current status of the thread by using the methods in this class.

[B] Note: {/B] You can create a class that allows the thread to run in two ways. One method is to inherit the Thread class, and the other is to inherit any class and implement the runnable interface. To facilitate the description, inheriting the Thread class is the simplest method. This method is used at the beginning of this book. In practice, implementing the runnable interface may work better.

In this example, the first step to create a new thread is to inherit the java. Lang. Thread class:

Java code
  1. Public class twothread extends thread {
  2. //...
  3. }
Public class twothread extends thread {//...}

The twothread subclass is a (IS-A) thread that inherits the protected and public members of the parent class. In addition to other behaviors inherited from the parent class, twothread can start, stop, interrupt, name, set the priority, and query the current state of the thread.

Override the run () method
After inheriting the Thread class, the next step is to override the run () method, because the methods in the Thread class do nothing:
Public void run (){}

When a new thread starts running, the entry to this thread is the run () method. The first statement in run () is the first statement executed by the new thread. Each statement executed by a thread is included in the run () method or other methods directly or indirectly called by the run () method. The new thread is considered to be alive from the time before run () is called to the time when run () is returned. After running () returns, the thread will die. When a thread is dead, it cannot be restarted.

In the examples in this chapter, the run () method is rewritten to iterate 10 times and the new thread information is printed each time:

Java code
  1. Public void run (){
  2. For (INT I = 0; I <10; I ++ ){
  3. System. Out. println ("New thread ");
  4. }
  5. }
Public void run () {for (INT I = 0; I <10; I ++) {system. Out. println ("New thread ");}}

After the loop is completed, the thread returns from the run () method and then dies quietly.

Create a new thread spawning a new thread
The new thread is created from a running thread. First, construct a new thread instance. In this example, a new twothread object will happen because the twothread IS-A thread:
Twothread TT = new twothread ();

The next step is to call the START () method to prepare to start the execution thread (START () inherited from the thread ):
TT. Start ();

Start () is returned immediately after the call and does not need to wait for other threads to start execution. In start (), the parent thread asynchronously sends a signal to the thread scheduler from JVM, telling it that other threads can start execution as long as it is convenient. In the future, other threads will be activated and the run () of the thread object will be called () method (in this example, it refers to the rewrite method run () implemented in twothread ()). At the same time, the original thread continues to execute the statement following the start () method.

Two threads run concurrently and independently. On a multi-processor machine, these two threads may actually run at the same time, and each thread runs on its own processor.

A more common case is that there is only one processor, and the JVM and OS work together to schedule each thread in a short time. When other threads are frozen and wait for the next opportunity of the processor, each thread gets a running opportunity. This kind of context switching between threads is very fast, giving you the illusion of simultaneous execution.

Tip: a newly created thread may start to execute (enter the run () method) at any time after start () is called ). This means that before any statement after the start () method is executed, the original thread may be swapped out (swapped out ).

Assume that the original thread is executing the following code:
Stmt1 ();
TT. Start ();

The new thread has a run () method as follows:

Java code
  1. Public void run (){
  2. Stmta ();
  3. Stmtb ();
  4. }
  5. Stmt2 ();
Public void run () {stmta (); stmtb () ;}stmt2 ();

The actual statement execution sequence in the processor may be stmt1 (), TT. Start (), stmt2 (), stmta (), and stmtb (). It may also be: stmt1 (), TT. Start (), stmta (), stmtb (), and stmt2 (). It may also be in another order.

It is important to remember that, although the order in which each thread executes its own statements is known and simple, the statements actually run on the processor are uncertain. There is no special order for Program correctness to depend on.

Put all together

Twothread. Java, shown in listing 2.1.
Listing 2.1 twothread. Java-the complete code for the twothread example

Java code
  1. 1: Public class twothread extends thread {
  2. 2: Public void run (){
  3. 3: For (INT I = 0; I <10; I ++ ){
  4. 4: system. Out. println ("New thread ");
  5. 5 :}
  6. 6 :}
  7. 7:
  8. 8: Public static void main (string [] ARGs ){
  9. 9: twothread TT = new twothread ();
  10. 10: TT. Start ();
  11. 11:
  12. 12: For (INT I = 0; I <10; I ++ ){
  13. 13: system. Out. println ("main thread ");
  14. 14 :}
  15. 15 :}
  16. 16 :}
1: Public class twothread extends thread {2: Public void run () {3: For (INT I = 0; I <10; I ++) {4: system. out. println ("New thread"); 5:} 6:} 7: 8: Public static void main (string [] ARGs) {9: twothread TT = new twothread (); 10: TT. start (); 11: 12: For (INT I = 0; I <10; I ++) {13: system. out. println ("main thread"); 14:} 15:} 16 :}

Result of the first running:
Main thread
New thread
Main thread
New thread
Main thread
New thread
Main thread
New thread
Main thread
New thread
Main thread
New thread
Main thread
New thread
Main thread
New thread
Main thread
New thread
Main thread
New thread

Result of the second run:

Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
Main thread
New thread
New thread
New thread
New thread
New thread
New thread
New thread
New thread
New thread
New thread
From the above results, we can see that the results of each operation are different, and your machine may also be different.

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.