Java Thread Third Edition first chapter thread introduction, chapter two thread creation and management learning notes

Source: Internet
Author: User
Tags set time


Chapter I. Introduction TO ThreadWhy do you use thread? Non-clogging I/O Multiplexing Technology Polling (polling) signal Warning (Alarm) and timer (timer) independent task parallel algorithm

chapter II creation and management of threadfirst, what is thread? Thread is an application task (Task) running on the host computer.


There is just one example of a thread:

public class Factorial {public static void main (string[] args) {int n = 5; System.out.print (n + "!) Is "), int fact = 1;while (n > 1) {fact *= n--;} SYSTEM.OUT.PRINTLN (fact);} Code to run the steps are top right to bottom//Java's entry is the Main method}




There are two examples of threads. i.e. two tasks, how will the application execute? varies depending on the conditions of the application being executed. repeated alternating execution of the computerWhy not use multiple applications to complete multiple tasks? Because thread is executed in the same application, they share the same memory space on the computer, so that information can be shared closely.
processes in a multi-tasking environment:

Threads in a multithreaded environment


second, create threadThread creation has two ways of inheriting from thread and implementing the Runnable interface with the use of
Thread constructor:
Thread ()           assigns a new thread object.

Thread (Runnable target) assigns a new thread object. The thread (Runnable target, String name) assigns a new thread object.

The thread (String name) assigns a new thread object. Thread (threadgroup group, Runnable target) assigns a new thread object.

Thread (threadgroup group, Runnable Target, String name) assigns a new thread object. To use target as its execution object, the specified name as its name. And as a member of the group of threads that the group refers to.

The thread (threadgroup group, Runnable Target, String name, long stackSize) assigns a new thread object so that the target is its executing object and the specified name as the Its name, as a member of the group of threads that the group refers to. and has the specified stack size. The thread (threadgroup Group, String name) assigns a new thread object.




third, the life cycle of thread1. Start thread
Class ThreadClass extends Thread {@Overridepublic void Run () {for (int i = 0; i < 5; i++) {System.out.println ("Helo Wor Ld! "+ i);}}} public class CreateThread {public void run () {for (int i = 0; i < 5; i++) {System.out.println ("Helo world!" + i);}} public static void Main (string[] args) {CreateThread ourclass = new CreateThread (); Ourclass.run (); ThreadClass ThreadClass = new ThreadClass (); Threadclass.start ();}}


Calling the Start method of the thread subclass runs the Run method. From log can be seen in two threads. But threads are all linear from the go-back run.
public void Run ()
Assuming that the thread is constructed using an independent Runnable execution object, the Run method of the Runnable object is called; The method does not perform whatever action and returns.
Subclasses of Thread should override this method.

public void Start () causes the thread to start running, and the Java virtual machine calls the thread's Run method.

The result is two threads executing concurrently, when the front thread (from the call is returned to the Start method) and a thread (executing its Run method). It is illegal to start a thread multiple times. Especially when the thread has ended running. Cannot be started again.
2. Thread's End thread's start-up runs the Run method, and when the method in run runs out of the last line, it ends naturally. Stop thread public final void Stop ()
is obsolete.

Forces the thread to stop running.
3. Thread suspend, suspend, resume hibernate public static void sleep (long Millis) throws Interruptedexception
Sleeps (suspends) the currently running thread within the specified number of milliseconds. This operation is affected by the accuracy and accuracy of the system timers and schedulers. The thread does not lose ownership of whatever monitor.


public static void sleep (long millis, int nanos) throws Interruptedexception
Sleeps (pauses) the currently running thread in the specified number of milliseconds plus the specified number of nanoseconds. This operation is affected by the accuracy and accuracy of the system timers and schedulers. The thread does not lose ownership of whatever monitor.


The simplest descriptive narrative of the Sleep () method is that the caller sleeps a set time.
4. Thread's aftercare threads connection public final void join (Long Millis) throws Interruptedexception
The maximum time to wait for the thread to terminate is Millis milliseconds. A timeout of 0 means you have to wait all the time.


Public final void Join (long millis, int nanos) throws Interruptedexception
The maximum time to wait for the thread to terminate is Millis milliseconds + Nanos nanoseconds.
Public final void Join () throws Interruptedexception
Waits for the thread to terminate.
Four, two ways to stop the thread 1. Mark

public class Randomcharactergenerator extends Thread {private volatile Boolean do = false; @Overridepublic void Run () {// ... while (!done) {//...} // ...} public void Setdone () {done = true;}}

The problem is that there will be a delay
2. Interrupts
Class Interruptedthread extends Thread {@Overridepublic void run () {if (!isinterrupted ()) {//}}}

public boolean isinterrupted ()
Whether the test thread has been interrupted.

The interrupt state of the thread is not affected by the method.
A thread break is ignored because a thread that is not active at the time of the outage is reflected by the method that returns false.
Return:
Assume that the thread has been interrupted. Returns TRUE, otherwise false is returned.


public static Boolean Interrupted ()
Tests whether the current thread has been interrupted.

The interrupt state of the thread is purged by this method. Other words. Assuming that the method is called twice in a row, the second call will return False (except in the case where the current thread is interrupted again until the first call has cleared the interrupt state and the second call has finished verifying the break state).


A thread break is ignored because a thread that is not active at the time of the outage is reflected by the method that returns false.



Return:
Assume that the current thread has been interrupted. Returns TRUE, otherwise false is returned.

v. Runnable Interface threads that use Runnable interfaces

public class Ourclass {public static void main (string[] args) {Runnableclass ourrunnableclass = new Runnableclass (); Thread thread = new Thread (ourrunnableclass); Thread.Start ();}} Class Runnableclass implements Runnable {@Overridepublic void Run () {for (int i = 0; i < 5; i++) {System.out.println ("H ELO world! "+ i);}}}


View Runnable Source code

six, thread and objectJudging the current threadpublic static Thread CurrentThread ()
Returns a reference to the currently running thread object.


Thread's life cycle public Final Boolean isAlive ()
Whether the test thread is active. It is active if the thread has been started and has not been terminated.
The name of the thread is public final void SetName (String name)
Change the thread name so that it is the same as the number of parameters.
The thread's CheckAccess method is called first, with no reference to any of the parameters. This may throw SecurityException.



Public final String GetName ()
Returns the name of the thread.

Public Thread (String name)
Assigns a new Thread object. Such a construction method has the same effect as Thread (null, NULL, name).

Public Thread (Threadgroup Group, String name)
Assigns a new Thread object.     Such a construction method has the same effect as Thread (group, NULL, name). Each thread is set to a name that facilitates the tracking and positioning of the problem.


Java Thread Third Edition first chapter thread introduction, chapter two thread creation and management learning notes

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.