Java study notes 44 (multithreading 1) and java Study Notes

Source: Internet
Author: User

Java study notes 44 (multithreading 1) and java Study Notes

Concept of multithreading: omitted

Multi-threaded objective: to improve efficiency

 

Main thread:

Package demo; // main thread public class Demo {public static void main (String [] args) {function (); System. out. println (1);} public static void function () {for (int I = 0; I <10000; I ++) {System. out. println (I );}}}

With this simple code, we found that:

The number 1 in the second row can be printed only after the method outputs the number of 10000 times.

Is there a way to execute the output of the second row while executing the method?

 

Thread class

There are two ways to create a new thread:

First:

Package demo; public class SubThread extends Thread {// override the run method public void run () {for (int I = 0; I <50; I ++) {System. out. println (I + "run ");}}}
package demo;public class ThreadDemo {    public static void main(String[] args) {        SubThread st1 = new SubThread();        st1.start();        for (int i = 0; i < 50; i++) {            System.out.println(i+"main");        }    }}

During the output, the printed run and main appear randomly and are staggered, instead of printing in order as before.

Cause: A New thread is created, and the two threads are selected and executed by the cpu, which cannot be controlled.

 

The start method starts a new Thread and inherits the Thread class because it can only operate on the Thread.

Override the run method because the Thread class itself does not write a meaningful run method, which is equivalent to a template for developers to use.

 

Thread Name:

Each Thread has its own name. The main Thread name is main, and the default name of other newly created threads is Thread-n.

Obtain and modify the thread Name:

 

Package demo1; public class NameThread extends Thread {public void run () {System. out. println (super. getName (); // output: The default value is Thread-0. If yes, It is hello }}
Package demo1; public class ThreadDemo {public static void main (String [] args) {NameThread nt1 = new NameThread (); nt1.setName ("hello"); // modify the thread name hello, the main Thread cannot be renamed nt1.start (); Thread t = Thread. currentThread (); System. out. println (t. getName (); // output: main }}

 

A Practical Method of the Thread class:

Package demo1; public class ThreadDemo {public static void main (String [] args) throws InterruptedException {for (int I = 0; I <10; I ++) {Thread. sleep (1, 1000); System. out. println (I);} // wait for one second for each printing. The parameter is a millisecond value }}

 

 

Method 2:

package demo1;public class SubRunnable implements Runnable {    public void run() {        for (int i = 0; i < 50; i++) {            System.out.println(i + "run");        }    }}
package demo1;public class ThreadDemo {    public static void main(String[] args) {        SubRunnable sr1 = new SubRunnable();        Thread t1 = new Thread(sr1);        t1.start();        for (int i = 0; i < 50; i++) {            System.out.println(i + "main");        }    }}

 

Advantages of this method:

1. Multiple Interfaces can be implemented to avoid the limitation of single inheritance.

2. Separation of threads and methods is more in line with object-oriented features

3. Share resources

 

The two methods can be used to implement anonymous internal classes:

Package demo1; public class ThreadDemo {public static void main (String [] args) {// Inheritance Method new Thread () {public void run () {System. out. println ("1 ");}}. start (); // interface implementation method new Thread (new Runnable () {public void run () {System. out. println (2 );}}). start ();}}

 

Thread status:

1. new State: new Thread () creates a Thread object

2. Running status: the start () method is used to enter the running status.

3. Exit status: the run method ends, or the stop method is called (expired, not recommended)

4. Blocking status: Sometimes the start method is used, but it may not be run immediately, or the CPU will not be allocated for some reason after running, from running status to blocking status

5. sleep Status: the sleep method mentioned above is in this status. It may also be switched to the blocking or running status.

6. Waiting status: wait method, unlimited waiting. The y method can wake up the thread and may be switched to running or blocking status.

Note: Blocking means waiting for CPU resources, while waiting for sleep means giving up CPU execution.

 

Concept of thread pool:

A container is saved to multiple threads. When necessary, it is executed,

The thread returns to the container after the running ends. This method can improve the efficiency.

Implementation thread pool:

Package demo1; public class ThreadPoolRunnable implements Runnable {public void run () {System. out. println (Thread. currentThread (). getName () + "thread submit task"); // output: pool-1-thread-1 thread submit task // pool-1-thread-2 thread submit task}
Package demo1; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class ThreadPoolDemo {public static void main (String [] args) {// call the factory class method to create the thread pool ExecutorService es1 = Executors. newFixedThreadPool (2); es1.submit (new ThreadPoolRunnable (); es1.submit (new ThreadPoolRunnable (); // es1.shutdown () is not stopped after running; // destroy the thread pool, not commonly used }}

 

Method for implementing the Callable interface of a thread:

It makes up for the defect of the Runnable method: An exception cannot be thrown and a return value exists.

The usage is basically the same as that of Runnable:

Example:

package demo1;import java.util.concurrent.Callable;public class ThreadPoolCallable implements Callable<String>{    public String call(){        return "a";    }}
Package demo1; import java. util. concurrent. executionException; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. future; public class ThreadPoolDemo {public static void main (String [] args) throws InterruptedException, ExecutionException {ExecutorService es1 = Executors. newFixedThreadPool (2); Future <String> f1 = es1.submit (new ThreadPoolCallable (); String s1 = f1.get (); System. out. println (s1); // get the returned value and output }}

 

 

Simple Application: multi-thread asynchronous computing

Calculate the sum using two threads:

package demo1;import java.util.concurrent.Callable;public class GetSumCallable implements Callable<Integer> {    private int a;    public GetSumCallable(int a) {        this.a = a;    }    public Integer call() {        int sum = 0;        for (int i = 0; i <= a; i++) {            sum += i;        }        return sum;    }}
package demo1;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class ThreadPoolDemo {    public static void main(String[] args) throws Exception {        ExecutorService es1 = Executors.newFixedThreadPool(2);        Future<Integer> f1 = es1.submit(new GetSumCallable(100));        Future<Integer> f2 = es1.submit(new GetSumCallable(300));        System.out.println(f1.get());        System.out.println(f2.get());        es1.shutdown();    }}

 

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.