Java Multithreading thread VS runnable detailed

Source: Internet
Author: User
Tags ticket high cpu usage

Requirements
      • Essential knowledge

        This article requires a basic understanding of Java programming knowledge.

      • Development environment

        Windows 7/editplus

      • Demo Address

        source file

Processes and Threads

A process is a run of a program in a processing machine. A process includes both the instructions to be executed and the system resources required to execute the instructions, and the system resources used by the different processes are relatively independent. So processes are heavyweight tasks, and the communication and conversion between them requires the operating system to pay a significant amount of overhead.

A thread is an entity in a process and is the basic unit that is dispatched and dispatched independently by the system. The thread itself basically does not own system resources, but it can share all the resources owned by the process with other threads belonging to one process. So threads are lightweight tasks, and the communication and conversion between them requires only a small system overhead.

Java supports multithreaded programming, so applications written in Java can perform multiple tasks at the same time. Java multithreading mechanism is very convenient to use, users only need to focus on the implementation of the details of the program, without worrying about the multi-tasking system in the background.

In the Java language, threads behave as thread classes. The thread threading class encapsulates all the required thread manipulation controls. When designing a program, you must clearly differentiate between the thread object and the running thread, and you can treat the threading object as a control panel that runs the thread. There are many ways to control whether a thread is running, sleeping, suspending, or stopping in the threaded object. Thread classes are the only means of controlling threading behavior. Once a Java program is started, a thread is already running. You can see which thread is currently running by calling the Thread.CurrentThread method.

Two methods of thread creation

Creating a thread in Java can create a thread by inheriting the thread class and implementing the Runnable interface. The runnable approach avoids the pitfalls of thread mode due to the Java single inheritance feature. Runnable code can be shared by multiple threads (thread instances) and is suitable for situations where multiple threads handle the same resource.

    • Inherit the thread class
class extends thread{.....     @Override    publicvoid  run () {    }}mythread mt=new  MyThread () ; Mt.start ();
    • Implementing the Runnable Interface
class Implements runnable{...    .    @Override    publicvoid  run () {    }}mythread mt=new  MyThread (); Thread td=new  thread (MT); Sd.start ();
Thread&runnable sold train tickets respectively
    • Thread mode
classMyThreadextendsthread{Private intticketscont=5;//There are 5 train tickets altogether .    PrivateString name;//window, which is also the name of the thread     PublicMyThread (String name) { This. name=name; } @Override Public voidrun () { while(ticketscont>0) {Ticketscont--;//If there's a ticket, sell a ticket.System.out.println (name+ "sold 1 tickets, the remaining votes:" +Ticketscont); }            }} Public classticketsthread{ Public Static voidMain (String args[]) {//create three threads, simulate three windows to sell a ticketMyThread mt1=NewMyThread ("Windows 1"); MyThread mt2=NewMyThread ("Windows 2"); MyThread Mt3=NewMyThread ("Windows 3"); //start three threads, that is, windows, start selling ticketsMt1.start ();        Mt2.start ();    Mt3.start (); }}
    • Runnable Way
classMyThread2Implementsrunnable{Private intticketscont=1000;//There are 5 train tickets altogether .@Override Public voidrun () { while(true){                 synchronized( This){                    if(ticketscont<=0){                         Break; } Ticketscont--;//If there's a ticket, sell a ticket.System.out.println (Thread.CurrentThread (). GetName ()+ "Sold 1 tickets, remaining votes:" +Ticketscont); /*try{Thread.Sleep (50);                    To view the effect by blocking the program} catch (Exception e) {System.out.println (e); }*/                }            }            }    /*@Override//No sync lock public void run () {while (ticketscont>0) {ticketscont--;//If you have a ticket, sell a ticket.        System.out.println (Thread.CurrentThread (). GetName () + "sold 1 tickets, remaining votes:" +ticketscont); }    }*/} Public classticketsrunnable{ Public Static voidMain (String args[]) {MyThread2 MT=NewMyThread2 (); //create three threads to simulate three ticketing windowsThread th1=NewThread (MT, "Window 1"); Thread Th2=NewThread (MT, "Window 2"); Thread Th3=NewThread (MT, "Window 3"); //start three threads, that is, three windows, start selling ticketsTh1.start ();        Th2.start ();            Th3.start (); }}
The life cycle of a thread

    • Create: Creates a new thread object, such as thread thd=new thread ()
    • Ready: After the thread object is created, the thread's start () method is called (at which point the thread knowledge enters the thread queue, waits for the CPU service, has the running condition, but does not necessarily start running)
    • Run: A thread in the ready state, once the CPU resource is acquired, it goes into the running state and starts executing the logic inside the Run () method
    • Terminate: The thread's Run () method finishes executing, or the thread calls the Stop () method, and the thread enters the terminating state
    • Blocking: An executing thread, in some cases, temporarily yielding CPU resources for some reason, pausing its own execution and entering a blocking state, such as calling the Sleep () method
Classification of threads
    • User threads: Running in the foreground, executing the main thread that has the task program, the child threads that connect to the network, etc. are user threads
    • Daemon: Running behind, serving other foreground threads. Once all user threads have finished running, the daemon will end up working with the JVM. You can set the current thread to be the daemon thread by calling the Setdaemon (true) method of the thread class, which must be called before the start () method, or the illegalthreadstateexception exception will be thrown. The new thread that is generated in the daemon thread is also the daemon thread. Not all tasks can be assigned to the daemon to perform, such as read-write operations or computational logic.
Daemon Thread test Case

Scenario: A main thread, a daemon thread, the daemon thread writes data to the local file for a long time, the main thread enters the blocking state waiting for the user's input, once the user's input blocking is confirmed, the main thread continues to run until the end, and the daemon ends with the virtual machine.

ImportJava.io.*;ImportJava.util.Scanner;classDaemonImplementsrunnable{@Override Public voidrun () {System.out.println ("Go to Guardian thread"); Try{writetofile (); }        Catch(Exception e) {e.printstacktrace (); } System.out.println ("Exit Daemon Thread"); }    Private voidWriteToFile ()throwsexception{File filename=NewFile ("f:/web (IMOOC)/Multi thread thread VS runnable/daemon.txt")); OutputStream OS=NewFileOutputStream (filename,true); intCount=0;  while(count<999) {Os.write ("\r\nword" +count). GetBytes ()); System.out.println ("Daemon Thread" +thread.currentthread (). GetName () + "write Word to File" +count++); Thread.Sleep (1000); }    }} Public classdaemonthreaddemo{ Public Static voidMain (String args[]) {System.out.println ("Go to main thread" +Thread.CurrentThread (). GetName ()); Daemon Daemonthread=NewDaemon (); Thread Thread=NewThread (Daemonthread); Thread.setdaemon (true);        Thread.Start (); Scanner SC=NewScanner (system.in);        Sc.next (); System.out.println ("Exit main thread" +Thread.CurrentThread (). GetName ()); }}

Test results

To generate a thread snapshot using Jstack

Jstack tools to the JDK installation directory under the Bin folder. Jstack can generate a snapshot of the current thread of the JVM (Threaddump, which is information for all threads in the current process). Help locator problems arise, such as prolonged pauses, high CPU usage, and so on.

How to use

Jstack [-l] <pid>: [-l] is optional, indicating that the two-bit information about the lock;<pid> represents the process ID.

Summarize

We recommend that you create threads this way using runnable. The same resource in the program refers to the same Runnable object. It is necessary to join the synchronous synchronized in the secure ticket selling procedure.

If the above articles or links are helpful to you, don't forget to click the "OK" button at the end of the article or click the "like a " button in the bottom right corner of the page. You can also click on the right side of the page " share " hover button Oh, let more people read this article.

Author: Li-cheng Source: http://www.cnblogs.com/Li-Cheng/p/4332179.htmldue to my limited level, the article in terms of presentation and code if there is something wrong, welcome criticism. Leave your footprints, welcome to comment Oh. You can also pay attention to me, study together Oh!

Java Multithreading thread VS runnable detailed

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.