Javase Learning 52: Detail the Thread class and runable interface in multiple threads

Source: Internet
Author: User
Tags ticket high cpu usage

Comparison of two ways to create a thread

There are two ways to create and start a thread, and this is just a list of steps that are no longer explained in detail.

(1) inherit the thread class

Class MyThread extends thread{public     void Run () {         ...     }} MyThread mt=new MyThread ();//Create Thread Mt.start ();//Start thread

(2) Implement runnable interface

Class MyThread implements runnable{public     void Run () {        ...     }} MyThread mt=new MyThread (); Thread Td=new thread (MT);//Create Thread Td.start ();//Start thread

(3) Comparison of two methods

1) The Runnable method avoids the defects caused by the Java single inheritance feature in thread mode.

2) The Code of the Runnable method can be shared by multiple threads (thread instances) and is suitable for situations where multiple threads handle the same resource.


Two simulating the application scenario

Simulate a train station to buy tickets for the scene, there are 5 train tickets left, there are three windows to sell the 5 train tickets, we use three threads to simulate three

window at the same time sell these 5 train tickets, we look at the thread way and Runnable Way These two ways simulate what kind of results.

(1) Use thread mode to simulate tickets

Ticketsthread.java Source file Code:

Class MyThread extends thread{//altogether has five train tickets private int ticketscount = 5;//window, that is, the name of the thread private String name;//construction method public MyThread (String name) {this.name = name;} public void Run () {while (Ticketscount > 0) {//If there is a ticket, sell a ticketscount--; System.out.println (name+ "sold 1 tickets, the remaining votes:" +ticketscount);}} public class Ticketsthread{public static void Main (string[] args) {//Create three threads, simulate three windows to buy tickets MyThread MT1 = new MyThread ("Window 1"); MyThread mt2 = new MyThread ("Window 2"); MyThread mt3 = new MyThread ("Window 3");//start three threads, i.e. the window starts selling tickets mt1.start (); Mt2.start (); Mt3.start ();}}

Operation Result:


The results are not the results we want.

The number of votes plus the static modifier keyword Get the result is correct. This is no longer a demonstration.

(2) using runnable mode to simulate tickets

Ticketsrunnable.java Source file Code:

Class MyThread1 implements runnable{//there are altogether five train tickets private int ticketscount = 5;public void Run () {while (Ticketscount > 0) {/ /If there is a ticket, sell a piece of ticketscount--; System.out.println (Thread.CurrentThread (). GetName () + "sold 1 tickets, remaining votes:" +ticketscount);}} public class Ticketsrunnable{public static void Main (string[] args) {MyThread1 mt = new MyThread1 ();//Create three threads, Simulate three windows to buy a ticket thread Th1 = new Thread (MT, "Window 1"); Thread Th2 = new Thread (MT, "Window 2"); Thread th3 = new Thread (MT, "Window 3");//Start three threads, that is, the window starts selling tickets th1.start (); Th2.start (); Th3.start ();}}

The expected results were obtained:


(3) Analysis of results

Because the execution of threads is random, the result of printing is also random.

Thread Mode

three threads, created three thread objects, each with its own thread object, has its own Ticketscount variables, three of them

threads are not shared ticketscount variables, i.e. each thread can sell 5 train tickets, or three windows to sell 15 train tickets.

Runnable Way

three threads share a Runnable object, that is, three threads share a Ticketscount variable, which is altogether three windows sold a total of 5 train tickets.

The former is not a thread three objects, is three thread object, is also three threads, these three threads start will execute 5 times to sell the ticket, implementation does not

Shared "5 Tickets" This resource, so the output will have 15 tickets sold out, obviously not in line with the actual, with runnable can solve the problem, create

Three threads can share the "5 tickets" resource.

The Ticketscont variable is an instance variable, and its value is naturally present in the heap (each Java object occupies a certain amount of memory in the heap, and the value of the instance variable

is stored in this memory, similar to the struct, so that each object corresponds to a Ticketscont value), Ticketscont is not related to the value passing, such as

If the result is a runnable way, it is only a copy of the Mythread object reference, regardless of ticketscont, but because the value of Ticketscont

In the heap memory pointed to by the reference and reference replicas, so whether a reference or a reference replica alters the value of Ticketscont in the heap memory, it will have an effect

Fruit!

This is based on your needs to operate, so to speak, if there is a relatively large resource for you to download, then you use the thread way then you can only one

A thread. This resource is downloaded, and if it's runable, you can get a new number of threads out of the way, by sharing the Runable object inside

Resources to download this resource with multiple threads, so that the Runable method will make the downloaded thread more likely to be in the CPU when downloading the resource

also allows you to download faster. Inheriting the thread class is the task of multiple threads accomplishing their own tasks, and implementing the Runnable interface is done together by multiple threads

a task.

The life cycle of a three-wire process

Life cycle transitions for threads:


The life cycle of a thread:

1) Create: Creates a new thread object, such as thread thd=new thread ().

2) Ready: After the thread object is created, the thread's start () method is called (note: The thread is just entering the thread queue, waiting to get the CPU service

Operating conditions, but not necessarily already started).

3) Run: The thread in the ready state, once the CPU resource is acquired, goes into the running state and starts executing the logic inside the run () method.

4) Blocking: An executing thread in some cases, for some reason, temporarily gave up the CPU resources, paused its own execution, then entered

A blocking state, such as a call to the sleep () method.

5) Termination: The thread's Run () method finishes executing, or the thread calls the Stop () method, and the thread enters the terminating state.

Here we can use a classic line problem is the example of producer and consumer issues:

Import java.util.*;p ublic class producerconsumer{public static void Main (string[] args) {syncstack ss = new Syncstack (); Producer p = new Producer (ss); Consumer C = new Consumer (ss); new Thread (P). Start (); new Thread (c). Start ();}} Production and Consumption object class Wotou{int ID;//constructor method Wotou (int id) {this.id = ID;} Override the ToString () method public String ToString () {return "Wotou:" + ID;}} Container class Syncstack{int index = 0; wotou[] ARRWT = new Wotou[4];p ublic synchronized void push (Wotou wt) {while (index = = arrwt.length) {try{//wait here () Method refers to the method in the object class This.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} The Notifyall () method here refers to waking all threads, while the Notify () method wakes up a thread this.notifyall (); Arrwt[index] = Wt;index + +;} Public synchronized Wotou POPs () {while (index = = 0) {try{//here the Wait () method refers to the method in the object class This.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} The Notifyall () method here refers to waking all threads, while the Notify () method wakes up a thread this.notifyall (); Index--;return arrwt[index];}} Producer Class Producer implements Runnable{syncstack SS = null; Producer (Syncstack ss) {THIS.Ss = SS;} public void Run () {for (int i=0; i<20; i++) {Wotou wt = new Wotou (i); ss.push (WT); System.out.println ("produced:" + wt); Try{thread.sleep ((int) (Math.random () * 200)); catch (Interruptedexception e) {e.printstacktrace ();}}}} Consumer class Consumer implements Runnable{syncstack SS = null; Consumer (Syncstack ss) {THIS.SS = SS;}            public void Run () {for (int i=0; i<20; i++) {Wotou wt = SS.POP (); System.out.println ("Consumed:" + wt); Try{thread.sleep ((int) (Math.random () * 1000)); catch (Interruptedexception e) {e.printstacktrace ();}}}}

Operation Result:


a few questions about the analysis:

The execution thread sleep () method is still occupied by the CPU, and the operating system considers that the current thread is running and does not yield system resources.

The wait () method is to allow the thread to wait for the pool to wait, letting out a series of system resources that other threads can use to schedule resources that consume CPU threads without

But should contain both CPU resources and lock resources.

Sleep (Long Mills): yields CPU resources, but does not release lock resources.

Wait (): Yields CPU resources and lock resources.

Locks are used for thread synchronization, and sleep (long mills) yields a CPU, but does not yield locks, while other threads can take advantage of CPU time slices, but

If another thread acquires a lock that is owned by sleep (long mills), it cannot execute because it cannot acquire a lock and continues to wait. But those who did not

A thread that competes with sleep (long Mills), once a CPU time slice is available to run .

Four daemon threads (1) Guardian Threading theory Knowledge

Java threads fall into two categories:

1) User thread: Run in the foreground and perform the specific task. The main thread of the program, the child threads that connect to the network, and so on are user threads.

2) Daemon Thread: Runs in the background and serves other foreground threads. The daemon thread is characterized by the routines of the guard line once all user threads have finished running

End the work with the JVM. Application of the daemon thread: the detection thread in the database connection pool and the detection thread after the JVM virtual machine is started, and so on. The most common

Daemon Thread: Garbage collection thread

To set the daemon thread:

You can set the current thread as the daemon thread by calling the Setdaemon (true) method of the thread class.

Considerations for using Daemon Threads:

1) Setdaemon (true) must be called before the start () method, or the illegalthreadstateexception exception will be thrown.

2) The new thread that is generated in the daemon thread is also the daemon thread.

3) Not all tasks can be assigned to the daemon to execute, such as read-write operations or computational logic.

(2) example of the daemon thread code:

Import Java.io.*;import Java.util.*;class Daemonthread implements runnable{public void Run () {System.out.println (" Enter the daemon thread "+thread.currentthread (). GetName ()); Try{writetofile ();} catch (Exception e) {e.printstacktrace ();} System.out.println ("Exit daemon Thread");} private void WriteToFile () throws exception{file filename = new File ("E:\\java\\javase\\thread" +file.separator+ " Daemon.txt "); OutputStream OS = new FileOutputStream (filename,true); int count = 0;while (Count < 999) {Os.write (("\r\nword" +count). GetBytes ()); System.out.println ("daemon" +thread.currentthread (). GetName () + "write Word to File" + count++); Thread.Sleep (1000);}} public class Daemonthreaddemo{public static void Main (string[] args) {System.out.println ("Go to main thread" +thread.currentthread (). GetName ());D aemonthread daemonthread = new Daemonthread (); Thread thread =new thread (daemonthread); Thread.setdaemon (true); Thread.Start (); Scanner sc = new Scanner (system.in); Sc.next (); SYSTEM.OUT.PRINTLN ("Exit Main thread" +thread.currentthread (). GetName ());}}

Operation Result:



(3) using Jstack to generate thread snapshots

Action: Generates a snapshot of the current thread of the JVM (Threaddump, which is information for all threads in the current process).

Objective: To help locate program problems, such as long-time pauses, high CPU usage.

Jstack command-line tools

You install the JDK directory under the Bin folder:

Location: E:\Java\develop\jdk1.8.0_25\bin


How to use Jstack

Input in cmd: jstack


We go to Task Manager to find the PID of a process:


To generate a snapshot:


Five Summary (1) How to solve the deadlock problem

1) Try to avoid unnecessary synchronized keywords.

2) You can replace the Synchronized keyword with another method, such as a flag that is not variable.

3) Ensure that the synchronized code block is concise.

(2) Suggestions for creating threads

Based on the comparison of two methods of creating threads, it is concluded that multithreading is better created using the method of implementing the Runnable interface, in addition, it is

It is important to note that the same resource in the program refers to the same Runnable object. It is recommended to use runnable this way to create multi-threading.

(3) Supplement:

1) The same resource in the program refers to the same Runnable object.

2) A secure ticketing procedure requires the addition of synchronization (Synchronized). Our code is not in the process, and if it needs to be perfected, it must be added

Sync lock.



Javase Learning 52: Detail the Thread class and runable interface in multiple threads

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.