Detailed explanation of multi-thread instances in java Work notes

Source: Internet
Author: User

I. Multithreading

1. What is multithreading?

It is easy to understand that multiple threads can execute multiple tasks at the same time. For example, downloading 10 URLs at the same time is much faster than downloading one URL at a time.
If you are interested in studying the principles, you can learn what thread and process is.

2. Small example of java multi-Thread method

Extends Thread-based multi-Thread experiment

3. runable example

2. java uses Runnable to implement multiline threads


Runnalbe can be used to create multiple threads. Previously, we used to inherit the Thread method.

The code is as follows: Copy code

Public class TestMitiThread1 implements Runnable {
 
Public static void main (String [] args ){
System. out. println (Thread. currentThread (). getName () + "The Thread starts running! ");
TestMitiThread1 test = new TestMitiThread1 ();
Thread thread1 = new Thread (test );
Thread thread2 = new Thread (test );
Thread1.start ();
Thread2.start ();
System. out. println (Thread. currentThread (). getName () + "The Thread stops running! ");
    }
 
Public void run (){
System. out. println (Thread. currentThread (). getName () + "The Thread starts running! ");
For (int I = 0; I & lt; 10; I ++ ){
System. out. println (I + "" + Thread. currentThread (). getName ());
Try {
Thread. sleep (int) Math. random () * 10 );
} Catch (InterruptedException e ){
E. printStackTrace ();
            }
        }
System. out. println (Thread. currentThread (). getName () + "The Thread stops running! ");
    }
}

Notes for java Multithreading


Multiple threads may encounter the main thread control. A single host distributes multiple tasks and how to know their respective fulfillment conditions. The subthread is required to report to the host.

1. Clarify the purpose. Why is multithreading required? If the bottleneck is caused by single-threaded read/write or network access (such as HTTP access to the Internet), you can consider using a thread pool. If you want to manage different resources (such as SOCKET connections), you can consider multiple threads.

2. When using a thread, pay attention to how to control the scheduling and blocking of the thread. For example, you can use the event trigger to control the scheduling and blocking of the thread, and also use messages to control the thread.

3. If public resources are used in a thread, the thread security of public resources must be considered. Generally, the LOCK mechanism is used to control thread security. Make sure there is no deadlock mechanism.

4. Reasonable use of sleep, when to Sleep, and Sleep size should be reasonably arranged according to the specific project. In general, SLeep is required for each loop in a non-blocking state, which ensures that the CPU is snatched by the thread is reduced. Every time a thread is ready and activated, it will occupy a certain amount of resources. If the thread body has multiple loops, multiple use of SLEEP will lead to performance degradation.

5. Thread Termination generally requires the thread body to terminate when a job is completed. Generally, do not directly terminate the thread by throwing a thread exception.

6. The thread priority must be planned based on the program's needs.

Thread inheritance

For common web crawlers, if you wait until the previous link is crawled, you can start the next one, instead of waiting until the ground is reached. This problem is easily solved by the use of multithreading technology.
Java multi-thread programming
1. Adding an extends Thread to the class is considered multithreading.
2. There must be a function called run ()

The code is as follows: Copy code
Package com. javaer. examples;
 
Public class ThreadExample extends Thread {
Public String color = "red ";
 
Public ThreadExample (String color ){
This. color = color;
 }
Public void run (){
// System. out. println (this. color );
For (int I = 0; I & lt; 3; I ++ ){
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
   }
System. out. println (this. color + "run" + I );
        }
 }
/**
* @ Param args
*/
Public static void main (String [] args ){
 
ThreadExample te = new ThreadExample ("red ");
ThreadExample te2 = new ThreadExample ("blue ");
Te. run ();
Te2.run ();
 
 }
 
}

Run () execution result

Red running 0
Red Run 1
Red Run 2
Run blue 0
Blue Run 1
Blue Run 2

For multi-threaded running, the two objects are executed in parallel in red and blue, so the results are output in the case of multi-threaded java.
Change
Te. start ();
Te2.start ();

Red running 0
Run blue 0
Red Run 1
Blue Run 1
Red Run 2
Blue Run 2

Remember that multi-threaded startup is te. start (), even though the executed function must be called run ();

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.