JAVA -- thread, java Multithreading

Source: Internet
Author: User

JAVA -- thread, java Multithreading

I believe that when I was learning JAVA, I was very impressed with the threads. Now, when I started to get started with Android development, I really found out how important the threads are, now I will share my understanding of the thread with you.

You must distinguishThreadAndProcessWhat is a process? The process is like executing the class file, and the thread actually calls the CPU resources to run it. A class file generally has only one process, but there can be many threads. asynchronous execution mode is used for thread execution.

It's useless. Let's go straight to the theme.

1. How to enable another thread in the main function:

Public class Thread_one {public static void main (String [] args) {Run run = new Run (); // run. run (); // This is a method call, which is quite different from the Thread thread Thread = new thread (run); Thread. start (); // start the thread and call the run () method of the thread for (int I = 1; I <= 20; I ++) {System. out. println ("main thread I value: --------" + I) ;}} class Run implements Runnable {@ Override public void run () {for (int I = 1; I <= 20; I ++) {System. out. println ("sub-thread I value:" + I );}}}

Ii. sleep method in the thread

Public class Thread_sleep {/** Thread pause */public static void main (String [] args) {Runone run = new Runone (); thread Thread = new Thread (run ); thread. start (); try {Thread. sleep (1, 5000); thread. interrupt (); // interrupt thread execution // thread. stop (); // relatively interrupted thread. It is too rough to stop. It is not recommended. This method is generally used when the subthread needs to be forcibly closed} catch (InterruptedException e) {e. printStackTrace () ;}} class Runone implements Runnable {@ Override public void run () {for (int I = 1; I <10; I ++) {try {Thread. sleep (1, 1000); System. out. println ("-----" + new Date () + "-----");} catch (InterruptedException e) {return; // when the capture sub-thread is interrupted, directly close the sub-thread }}}}

Specifically, thread. interrupt (); can interrupt thread execution. It is a little bit gentle than stop, but it is not the best way to close the thread. The following provides a way for you:

Public class Thread_stop {public static void main (String [] args) {Runthree run = new Runthree (); Thread th = new Thread (run); th. start (); try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} run. setStop () ;}} class Runthree implements Runnable {boolean flag; @ Override public void run () {flag = true; int I = 0; while (flag) {try {System. out. println ("sub-Thread ----" + (I ++); Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace () ;}} public void setStop () {flag = false ;}}

Next we will briefly introduce the merge and transfer in the thread:

I. How to merge threads, here the join () method is called

Public class Thread_join {/** merge Thread */public static void main (String [] args) {Runtwo run = new Runtwo (); thread Thread = new Thread (run ); thread. start (); try {thread. join (); // merge threads, which is equivalent to method call} catch (InterruptedException e) {e. printStackTrace () ;}for (int I = 0; I <10; I ++) {System. out. println ("main thread:" + I) ;}} class Runtwo implements Runnable {@ Override public void run () {for (int I = 0; I <10; I ++) {System. out. println ("sub-thread: ----" + I );}}}

Ii. How to let the Thread out, the yield () method of the Thread is called here:

Public class Thread_yield {/** let out CPU * @ param args */public static void main (String [] args) {Th th = new Th ("aaa"); th. start (); for (int I = 0; I <= 10; I ++) {System. out. println ("main Thread ----" + I) ;}} class Th extends Thread {Th () {}th (String s) {super (s );} @ Override public void run () {for (int I = 0; I <= 10; I ++) {if (I % 3! = 0) {System. out. println ("sub-thread" + I);} else {System. out. println ("sub-Thread I =" + I + ""); yield (); // This method can be used only after it is inherited from Thread }}}}

Finally, I would like to share with you the question about thread priority:

Public class Thread_priority {/** priority sets the Thread priority * the default Thread priority is 5; the maximum Thread priority is 10, the minimum value is 0 */public static void main (String [] args) {T1 t1 = new T1 (); T2 t2 = new T2 (); t1.start (); // t1.setPriority (Thread. NORM_PRIORITY + 3); // set t2.start ();} class t1 extends Thread {@ Override public void run () {for (int I = 0; I <50; I ++) {System. out. println ("Thread T1 -----" + I) ;}} class T2 extends Thread {@ Override public void run () {for (int I = 0; I <50; I ++) {System. out. println ("thread T2" + I );}}}

I believe that you have basically understood the thread mechanism in JAVA through the above Code. For thread synchronization, I will communicate with you in the next article. If you have any questions, please feel free to harass.

Finally, I would like to provide some advice if any of the above content is incorrect.


What is java multithreading?

A process is a program running in a processor. A process includes both the command to be executed and the system resources required for executing the command. The system resources occupied by different processes are relatively independent. Therefore, processes are heavyweight tasks, and communication and conversion between them both require a large overhead of the operating system.
A thread is an entity in a process and the basic unit of independent scheduling and distribution by the system. A thread basically does not own system resources, but it can share all resources of a process with other threads of the same process. Therefore, threads are lightweight tasks, and communication and conversion between them only requires a small amount of system overhead.
Java supports multi-threaded programming. Therefore, applications written in Java can execute multiple tasks at the same time. Java's multithreading mechanism is very convenient to use. Users only need to pay attention to the implementation of program details, rather than worrying about background multi-task systems.
In Java, threads are represented as thread classes. The Thread class encapsulates all required Thread operation controls. When designing a program, you must clearly distinguish the thread object from the running thread. You can regard the thread object as the control panel of the running thread. There are many methods in the thread object to control whether a thread is running, sleep, suspended, or stopped. The thread class is the only means to control thread behavior. Once a Java program is started, a thread is running. You can call the Thread. currentThread method to check which Thread is currently running.

Class ThreadTest {
Public static void main (String args []) {
Thread t = Thread. currentThread ();
T. setName ("single thread"); // name a single thread"
T. setPriority (8 );
// Set the thread priority to 8, the highest is 10, the lowest is 1, the default is 5
System. out. println ("The running thread:" + t );
// Display thread Information
Try {
For (int I = 0; I <3; I ++ ){
System. out. println ("Sleep time" + I );
Thread. sleep (100); // sleep 100 ms
}
} Catch (InterruptedException e) {// catch an exception
System. out. println ("thread has wrong ");
}
}
}

Multi-thread implementation
Inherit Thread class
You can inherit the Thread class and override the run () method to define the Thread body to implement the specific behavior of the Thread, and then create the object of this subclass to create a Thread.
In the ThreadSubclassName subclass that inherits the Thread class, override the run () method to define the general format of the Thread body:
Public class ThreadSubclassName extends Thread {
Public ThreadSubclassName (){
... // Compile the constructor of the subclass. The default value can be used.
}
Public void run (){
... // Write your own thread code
}
}
The general format of creating a thread object using the defined thread subclass ThreadSubclassName is:
ThreadSubclassName ThreadObject =
... The remaining full text>

Java thread Problems

The runnable interface is not the difference between the Runnable interface of the Thread class and the Thread class. If a Thread implements the Runnable interface, when the object that calls this Thread opens up multiple threads, these threads can call the same variable. If the Thread is inherited from the Thread class, the above functions should be implemented through the internal class, the internal class can access the external variables at will. Example program: public class ThreadTest {public static void main (String [] args) {MyThread mt = new MyThread (); new Thread (mt ). start (); // open the first Thread new Thread (mt) by implementing the Runnable class object ). start (); // open the second Thread new Thread (mt) by implementing the Runnable class object ). start (); // open up the third thread by implementing the Runnable Class Object // because these three threads are opened through the same object mt ,... hope to help you!
 

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.