Basic concepts of Java multithreaded _01_ threads

Source: Internet
Author: User
Tags thread class

Threads: Different execution paths inside a program

Example program: This example program is an execution path. This program has only one branch, is the main method, called the main thread

 Public Static void Main (string[] args) {        m1 ();    }      Public Static void M1 () {        m2 ();        M3 ();    }      Public Static void m2 () {}      Public Static void m3 () {}

Program execution:

Process: A process is a static concept, a class file on the machine, an EXE file.

Program execution process, to put the code of the program into memory, put in the code area, a process is ready to start, the process has been generated, but has not started execution, which is called the process. is a static concept. Usually say the process of execution said that the process inside the main thread began to execute. Running in the machine is actually a thread.

Our Windows runs multiple threads at the same time, so the machine supports multithreading. And of course support multiple processes. Windows, Linux, Unix are multi-process, multi-threaded, DOS is only support single-process, the same point in time can only perform one process execution.

The CPU calculates the speed quickly, divides own time into the time slice, this time slice executes you a moment, the next time slice executes it a moment, the wheel comes. Although there are dozens of threads, the rotation is performed as quickly as it seems to us as if multiple threads were executing at the same time. But actually, at a point in time, the cup has only one thread running. (If the machine is multi-core, there are multiple CPUs, is the real multi-threaded)

Implement the Runnable interface:
 Packagethread; Public classTESTTHREAD01 { Public Static voidMain (string[] args) {Runner1 R=NewRunner1 (); Thread T=NewThread (R); T.start ();//starts the thread, notifies the CPU that the thread is ready, and is free to execute me for a while .                 for(inti = 0; I < 100; i++) {System.out.println ("------Main Thread:" +i); }    }}classRunner1Implementsrunnable{@Override Public voidrun () { for(inti = 0; I < 100; i++) {System.out.println ("Runner1:" +i); }    }}

Execution results: Wheel execution

Inherit the thread class:
 Packagethread; Public classTESTTHREAD01 { Public Static voidMain (string[] args) {Runner1 R=NewRunner1 (); R.start ();//itself is thread, call start directly//thread t = new Thread (r);//T.start ();//starts the thread, notifies the CPU that the thread is ready, and is free to execute me for a while .                 for(inti = 0; I < 100; i++) {System.out.println ("------Main Thread:" +i); }    }}//class Runner1 implements runnable{classRunner1extendsthread{@Override Public voidrun () { for(inti = 0; I < 100; i++) {System.out.println ("Runner1:" +i); }    }}

The thread class is not inherited if the interface can be implemented.

state transitions for threads:

A thread class, new comes out just an object in memory. The Start method is called, not immediately, but in a ready state, queued because the CPU may be executing other threads. The CPU is happy and the object is tuned to the CPU to be executed. In the course of execution, you may end up with your time slice and return to the ready state to line up, waiting for your next turn, until it is done.

During the run, there may be situations where you have to wait until the situation is resolved before you can continue running, which is called blocking state.

The higher the priority thread, the more time it takes for the CPU to execute.

Sleep:
 Packagethread;ImportJava.util.*; Public classTestinterrupt { Public Static voidMain (string[] args) {MyThread thread=NewMyThread (); Thread.Start ();//activation Thread        Try {            //The main thread sleeps for 10 seconds, performs the mythread, prints 10 hours .Thread.Sleep (10000); } Catch(Interruptedexception e) {}//after printing 10 time to do this, call the interrupt method in the thread break. Thread.Interrupt (); }}classMyThreadextendsThread {BooleanFlag =true;  Public voidrun () { while(flag) {System.out.println ("===" +NewDate () + "= = ="); Try{sleep (1000); } Catch(interruptedexception e) {return; }        }    }}

Result: After printing 10 time, the thread ends. once the Run method is finished, the thread ends.

===mon June 22:19:40 CST 2017===
===mon June 22:19:41 CST 2017===
===mon June 22:19:42 CST 2017===
===mon June 22:19:43 CST 2017===
===mon June 22:19:44 CST 2017===
===mon June 22:19:45 CST 2017===
===mon June 22:19:46 CST 2017===
===mon June 22:19:47 CST 2017===
===mon June 22:19:48 CST 2017===
===mon June 22:19:49 CST 2017===

Join: Merge a thread (wait for the thread to terminate)

Code:

 Packagethread; Public classTestjoin { Public Static voidMain (string[] args) {MyThread2 T1=NewMyThread2 ("ABCDE");    T1.start (); Try {        /*** Merge the T1 thread into the main thread, that is, wait for the T1 thread to finish executing, and then execute the main thread * equivalent to the method call*/T1.join (); } Catch(Interruptedexception e) {}//when the T1 is done, the opportunity to execute the     for(inti=1;i<=10;i++) {System.out.println ("I am Main thread"); }  }}classMyThread2extendsThread {MyThread2 (String s) {//give the thread a name      Super(s); }     Public voidrun () { for(intI =1;i<=10;i++) {System.out.println ("I am" +getName ()); Try{sleep (1000); } Catch(interruptedexception e) {return; }    }  }}

Join merges the T1 into the main thread, and main waits for T1 to execute itself.

Results:

I am ABCDE
I am ABCDE
I am ABCDE
I am ABCDE
I am ABCDE
I am ABCDE
I am ABCDE
I am ABCDE
I am ABCDE
I am ABCDE
I am Main thread
I am Main thread
I am Main thread
I am Main thread
I am Main thread
I am Main thread
I am Main thread
I am Main thread
I am Main thread
I am Main thread

Yield:
 Packagethread; Public classTestyield { Public Static voidMain (string[] args) {MyThread3 T1=NewMYTHREAD3 ("------T1"); MYTHREAD3 T2=NewMyThread3 ("T2");    T1.start ();  T2.start (); }}classMyThread3extendsThread {MyThread3 (String s) {Super(s);}  Public voidrun () { for(intI =1;i<=100;i++) {System.out.println (GetName ()+": "+i); if(i%10==0) {//can be divisible by 10, make time slices, not obviousyield (); }    }  }}

Result: should be evenly divisible by 10, let the other threads, but not obvious.

------T1:1
------T1:2
------T1:3
------T1:4
------T1:5
------T1:6
------T1:7
------T1:8
------T1:9
------T1:10
T2:1
T2:2
T2:3
T2:4
T2:5
T2:6
------T1:11

。。。。。

Priority of the thread:
 Packagethread; Public classtestpriority { Public Static voidMain (string[] args) {Thread T1=NewThread (NewT1 ()); Thread T2=NewThread (NewT2 ()); T1.setpriority (thread.norm_priority+ 3);        T1.start ();    T2.start (); }}classT1ImplementsRunnable { Public voidrun () { for(inti=0; i<1000; i++) {System.out.println ("T1:" +i); }    }}classT2ImplementsRunnable { Public voidrun () { for(inti=0; i<1000; i++) {System.out.println ("------T2:" +i); }    }}

Result: Not obvious

t1:0
T1:1
T1:2
T1:3
T1:4
T1:5
T1:6
T1:7
T1:8
T1:9
T1:10
T1:11
T1:12
T1:13
T1:14
T1:15
T1:16
T1:17
T1:18
T1:19
T1:20
T1:21
T1:22
T1:23
T1:24
T1:25
T1:26
T1:27
T1:28
T1:29
T1:30
T1:31
T1:32
T1:33
T1:34
T1:35
T1:36
T1:37
t1:38
t1:39
T1:40
t1:41
T1:42
t1:43
T1:44
T1:45
t1:46
T1:47
t1:48
t1:49
T1:50
T1:51
t1:52
t1:53
t1:54
T1:55
t1:56
t1:57
t1:58
t1:59
T1:60
t1:61
t1:62
t1:63
T1:64
T1:65
t1:66
t1:67
t1:68
t1:69
T1:70
t1:71
t1:72
t1:73
t1:74
T1:75
t1:76
T1:77
t1:78
t1:79
T1:80
t1:81
t1:82
t1:83
t1:84
T1:85
T1:86
t1:87
t1:88
t1:89
T1:90
t1:91
t1:92
t1:93
t1:94
T1:95
t1:96
t1:97
T1:98
t1:99
t1:100
T1:101
t1:102
t1:103
t1:104
t1:105
t1:106
t1:107
t1:108
t1:109
t1:110
------t2:0
t1:111
------T2:1
t1:112
------T2:2
t1:113
------T2:3
t1:114

Basic concepts of Java multithreaded _01_ 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.