Basic knowledge of Thread thread, basic knowledge of Thread thread

Source: Internet
Author: User
Tags time in milliseconds

Basic knowledge of Thread thread, basic knowledge of Thread thread

1. Basic concepts of threads

1. Sequential Control Flow Within a program in a city.

2. Java threads are implemented through the java. lang. Thread class.

3. When the VM is started, there will be a thread defined by the main method {public static void main (Args [] String.

4. You can create a Thread by creating a new Thread instance.

5. Each Thread performs operations through the method run () corresponding to a specific Thread object. The method run () is called the Thread body.

6. Call the start () method of the Thread class to start a Thread.

Note: multi-process (multiple tasks (programs) can be run simultaneously in the operating system) and multi-thread (multiple sequential streams are executed simultaneously in the same application ).

Ii. Thread Creation

 1. Define the Thread class to implement the Runnable interface(Recommended, more flexible):

Thread thread = new Threa (target); // target indicates the Runnable interface type;

Runnable has only one method: public void run (); // used to define the thread runtime body.

    *EnableThe Runnable interface can be used to provide shared data for multiple threads.

In the run method definition of the class implementing the Runnable interface, you can use the static method of Thread:

Public static Thread currentThread () gets the reference of the current Thread.

Public class ThreadTheory {public static void main (String args []) {Runner1 runner1 = new Runner1 (); Thread thread = new Thread (runner1); thread. start (); for (int I = 0; I <10; I ++) {System. out. println ("Main Thread:" + I) ;}} public class Runner1 implements Runnable {public void run () {for (int I = 0; I <10; I ++) {System. out. println ("Runner1:" + I );}}}View Code

2. inherit the Thread class and override the run method:

Class MyThread extends Thread {

Public void run (){......}

}

Then generate the object of this class:

MyThread myThread = new MyThread (...);

Public class ThreadTheory {public static void main (String args []) {Runner2 runner2 = new Runner2 (); runner2.start (); // runner2 itself is a thread, no new Thread (); for (int I = 0; I <10; I ++) {System. out. println ("Main Thread:" + I) ;}} public class Runner2 extends Thread {public void run () {for (int I = 0; I <10; I ++) {System. out. println ("Runner2:" + I );}}}View Code

 

III. Basic thread control methods

     

Sleep (thread. sleep (long millis ))
    public static void sleep(long millis) throws InterruptedException
Sleep the currently running thread (paused) within a specified millisecond ). This thread does not lose the ownership of any monitor.
Parameters:
millis-Sleep Time in milliseconds.
Throw:
InterruptedException-If another thread breaks the current thread. When this exception is thrown Interruption statusCleared.

 

Interrupt (thread. interrupt ())
    public void interrupt()
Interrupt thread.

If the current thread does not interrupt itself (which is allowed in any case ),checkAccessThe method will be called, which may throwSecurityException.

If the thread is callingObjectClasswait(),wait(long)Orwait(long, int)Method, orjoin(),join(long),join(long, int),sleep(long)Orsleep(long, int)When the method is blocked, the disconnection status is cleared, and it also receivesInterruptedException.

If the threadBroken ChannelsIf the I/O operation on the thread is blocked, the channel will be closed, the thread's interruption status will be set, and the thread will receiveClosedByInterruptException.

If the thread is inSelectorIs blocked, the thread's interruption status will be set, it will immediately return from the selection operation, and may have a non-zero value, as if the selector'swakeupSame method.

If none of the preceding conditions are saved, the thread interruption status is set.

Throw:
SecurityException-If the current thread cannot be modified

  

Note: comfortable way to end the thread (reject violence ):

Public class ThreadTheory {public static void main (String args []) {MyThread myThread = new MyThread (); myThread. start (); try {Thread. sleep (10000);} catch (InterruptedException e) {} myThread. stopThread (); // end Thread by flag} public class MyThread extends Thread {private boolean flag = true; public void stopThread () {this. flag = false;} public void run () {while (flag) {System. out. println ("= Current Time" + new Date () + "="); try {sleep (1000);} catch (InterruptedException e) {return ;}}}}View Code

 

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.