Summarizing the state of Java thread and the way to realize multithreading _java

Source: Internet
Author: User
Tags thread class ticket cpu usage

The state of the thread
Thread state diagram:

Description
A thread consists of the following 5 states altogether.
1. New State: After the thread object is created, it enters the new state. For example, thread thread = new Thread ().
2. Ready status (Runnable):Also known as "executable state." When a thread object is created, the other thread invokes the object's start () method to start the thread. For example, Thread.Start (). A thread in the ready state may be scheduled to execute by the CPU at any time.
3. Operating status (Running):The thread acquires CPU permissions for execution. It should be noted that the thread can only move from the ready state to the running state.
4. Blocking status (Blocked):A blocking state is a thread that, for some reason, discards CPU usage and temporarily stops running. Until the thread enters the ready state, there is an opportunity to go to the running state. The blocking situation is divided into three types:
(1) Wait for blocking--by invoking the thread's Wait () method, the thread waits for the completion of a work.
(2) Synchronous blocking-the thread fails to acquire the synchronized synchronization lock (because the lock is occupied by another thread) and it enters the synchronized blocking state.
(3) Other blocking--the thread enters the blocking state by calling the thread's sleep () or join () or sending an I/O request. When the sleep () state times out, join () waits for the thread to terminate or timeout, or the I/O process completes, the thread is back in ready state.
5. State of Death (Dead):The thread ends the lifecycle by executing the thread or exiting the run () method because of an exception.
The 5 states involved include the object class, thread and synchronized keywords. We will study each of these in the following chapters.
Object class, which defines a wait (), notify (), Notifyall (), and so on hibernate/wake functions.
Thread class, which defines some of the column's threading action functions. For example, the sleep () Hibernate function, the interrupt () interrupt function, GetName () Gets the thread name, and so on.
Synchronized, is the keyword; it is differentiated into synchronized code blocks and synchronized methods. The role of synchronized is to let the thread get the synchronized lock of the object.
When we go into the details of wait (), notify (), and so on, we'll analyze Why "wait (), notify (), and so on, are defined in the object class, not in the thread class."

Two ways to implement Multithreading: Thread and Runnable
Runnable is an interface that contains only one run () method. It is defined as follows:

Public interface Runnable {public
  abstract void Run ();
}

Runnable the role of multithreading to achieve. We can define a class A to implement the Runnable interface, and then create a new thread by using new thread (new A ()).
Thread is a class. Thread itself implements the Runnable interface. Its statement is as follows:
public class Thread implements Runnable {}
Thread of the role, to achieve multithreading.

The similarities and differences between thread and runnable:
thread and Runnable the same point: are "multithreading implementation."
Different points of Thread and Runnable:
Thread is a class, and runnable is an interface; thread itself is a class that implements the Runnable interface. We know that "a class can have only one parent class, but it can implement multiple interfaces", so runnable has better extensibility.
In addition, runnable can also be used for "sharing resources." That is, multiple threads are based on a single Runnable object, and they share resources on the Runnable object.
Generally, it is recommended to implement multithreading through "Runnable"!
thread and runnable examples of multithreading
1.Thread Multithreaded Example
The following example provides a better understanding of thread and runnable, using an example on the Web to compare persuasive examples. Threadtest.java Source

Class Mythread extends thread{
  private int ticket=10; 
  public void Run () {-for
    (int i=0;i<20;i++) { 
      if (this.ticket>0) {
        System.out.println (this.getname () + "Sell Tickets: Ticket" +this.ticket--);
      }}} 
;

public class ThreadTest {public 
  static void Main (string[] args) { 
    //starts 3 threads t1,t2,t3; Each thread sells 10 tickets each!
    mythread t1=new mythread ();
    Mythread t2=new mythread ();
    Mythread t3=new mythread ();
    T1.start ();
    T2.start ();
    T3.start ();
  } 
 

Run Result:

Thread-0 Selling Tickets: ticket10
Thread-1 Selling Tickets: ticket10 Thread-2 selling Tickets: ticket10 Thread-1
Selling Tickets:
ticket9 Thread-0 Selling tickets: Ticket9 Thread-1 selling Tickets: Ticket8 Thread-2 selling Tickets: Ticket9 Thread-1 selling Tickets: ticket7 Thread-0
Selling tickets:
ticket8 Thread-1 Selling Tickets: Ticket6
Thread-2 Selling Tickets: Ticket8 Thread-1 selling Tickets: Ticket5 Thread-0
Selling Tickets:
ticket7 Thread-1 Selling tickets: Ticket4 Thread-2 selling Tickets: Ticket7 Thread-1 selling Tickets: Ticket3 Thread-0 selling Tickets: Ticket6 Thread-1
selling Tickets: Ticket2
Thread-2 Selling Tickets: Ticket6
Thread-2 Selling Tickets: Ticket5
Thread-2 Selling Tickets: Ticket4 Thread-1 selling Tickets: Ticket1 Thread-0
Selling Tickets:
ticket5 Thread-2 Selling tickets: Ticket3 Thread-0 selling Tickets: Ticket4 Thread-2 selling Tickets: Ticket2 Thread-0 selling Tickets: Ticket3 Thread-2
selling Tickets: Ticket1
Thread-0 Selling Tickets: Ticket2
Thread-0 Selling Tickets: Ticket1

Results show:
(1) Mythread inherits from Thread, which is a custom thread. Every mythread will sell 10 tickets.
(2) Main thread main to create and start 3 mythread child threads. Each child thread has sold 10 tickets each.

2.Runnable Multithreaded Example
Next, we make changes to the above program. Implement an interface through runnable to achieve multithreading.

Runnabletest.java source
class Mythread implements runnable{ 
  private int ticket=10; 
  public void Run () {-for
    (int i=0;i<20;i++) { 
      if (this.ticket>0) {
        System.out.println ( Thread.CurrentThread (). GetName () + "Sell Tickets: Ticket" +this.ticket--);}}} 
; 

public class Runnabletest {public 
  static void Main (string[] args) { 
    mythread mt=new mythread ();

    Start 3 thread t1,t2,t3 (they share a runnable object), these 3 threads sell 10 tickets altogether!
    thread T1=new Thread (MT);
    Thread T2=new thread (MT);
    Thread T3=new thread (MT);
    T1.start ();
    T2.start ();
    T3.start ();
  } 


Run Result:

Thread-0 Selling Tickets: ticket10
Thread-2 Selling Tickets: Ticket8 Thread-1 selling Tickets: Ticket9 Thread-2
Selling Tickets:
Ticket6 Thread-0 Selling tickets: Ticket7 Thread-2 selling Tickets: Ticket4 Thread-1 selling Tickets: Ticket5 Thread-2 selling Tickets: Ticket2 Thread-0
selling Tickets: Ticket3
Thread-1 Selling Tickets: Ticket1

Result Description:
(1) is different from "Mythread inherits from Thread" above; the Mythread implements the thread interface. The
(2) main thread main creates and starts 3 child threads, and the 3 child threads are created based on the Mt this runnable object. The result was a total of 10 tickets sold for the 3 child threads. This means that they are shared with the Mythread interface.

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.