java Concurrency Principle Reality--How to Create Threads

Article Directory

Create Threads

1. Inherit thread

Execution process:

Clients call the start() method - - private native void start0(); - control is given to jvm - - execute the parent run() method overridden by the thread when the resource is seized

Instance code:

public class Demo1 extends Thread {
    public Demo1(String name) {
        super(name);
    }
    @Override
    public void run() {
        while(!interrupted()){
            System.out.println(getName()+ " Thread executed....");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Demo1 demo1 = new Demo1("Thread 1");
        demo1.start();
    }
}

Run result:

2. Implement the runnable interface:

Execution process:

As a threaded task: what a thread does is sort threads and tasks, make code decouple threads--new thread(target)--init method passes global target assignments to the current threaded task--jvm call--target.run method

English translation:

  • 1. If this thread is constructed using a separate Runnable run object, the run method of the Runnable object will be called; * Otherwise, the method will do nothing and return.
  • 2. Subclasses of `Thread'should override this method.

This is the first case where the run method of the runable object we passed is called.

Instance code:

public class Demo2 implements Runnable{
    @Override
    public void run() {
        while(true){
            System.out.println("thread running ...");
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new Demo2());
        thread.start();

    }
}

Run result:

3. How anonymous internal classes work:

Essential: When there is only one thread, the instance does not need to be named anymore, and is simply new and reused, it is also the result of the above two ways of execution.

1. Override thead class + anonymous inner class

  public static void main(String[] args) {
        //Anonymous internal classes can be used if there is only one thread
        //Using an anonymous internal class, equivalent to a thread subclass
        new Thread(){
            @Override
            public void run() {
                System.out.println("thread start1....");
            }
        }.start();
   }

Implement runnable+anonymous inner class

 //Pass Thread Task as Parameter
        new Thread(new Runnable(){
            @Override
            public void run() {
                System.out.println("thread start2....");
            }
        }).start();

(3) Implement runnable+override thead class+anonymous internal class

That's fine, but I don't usually do much.

    //Pass Thread Task as Parameter
        new Thread(new Runnable(){
            @Override
            public void run() {
                System.out.println("thread start2....");
            }
        }){
            @Override
            public void run() {
                System.out.println("thread start1....");
            }
        }.start();

Run result: thread start1...

Why?

This refers to the knowledge of dynamic assignment of method calls in jvm: that is, the principle of method overrides.

The runable interface is implemented and passed in as a thread task parameter, but the jvm calls the run of the subclass when it executes, regardless of the run method of its own class, and will not execute even if there is a target.

Subclass thread s override the run method. Based on the principle of jvm method overrides, dynamic assignment of method calls the run method of subclass

4. Create threads with both returns and exceptions

Do not care what the principle is, but add it later. The code demonstrates as follows:

public class Demo4  implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("Tense calculations are in progress");
        Thread.sleep(3000);
        return 1;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //Tasks as Executed
        Demo4 demo4 = new Demo4();
        //encapsulation
        FutureTask<Integer> task = new FutureTask<>(demo4);
        //Wrap to thread class
        Thread thread = new Thread(task);
        thread.start();
        System.out.println("Let me do something else first");
        //Get results
        Integer result = task.get();
        System.out.println(result);
    }
}

Run result:

Run the thread and return the value, cow.

5. Timer

timer

Look at his api:


Code demonstration:

public class Demo5 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("timetask is run");
            }
        },0,1000);
    }
}

Run result:

Disadvantages:

When a Timer runs more than one TimerTask, as long as one of the TimerTasks is executing toward the run method
If an exception is thrown, other tasks will automatically terminate.

5. Thread Pool


​```java
public class Demo6 {
​ public static void main(String[] args) {
//10 Thread Pools
​ ExecutorService threadPool = Executors.newFixedThreadPool(10);
​ for (int i=0;i<100;i++){
//Create Thread Task
​ threadPool.execute(new Runnable() {
​ @Override
​ public void run() {
​ System.out.println(Thread.currentThread().getName());
​ }
​ });
​ }
//Stop Thread Pool
​ threadPool.shutdown();
​ }
}

Run result:


//Displays the creation of 10 threads, each thread does its work and then does it, so not 10 threads each do 10 times, some do more, some do less.Ten thread attacks executed 100 times.

//Demo 2:

​```java
public class Demo6 {
    public static void main(String[] args) {
        //Automatically create the size of the thread pool, create it when it's not enough, and recycle when it's used up.
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for (int i=0;i<100;i++){
            //Create Thread Task
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
        //Stop Thread Pool
        threadPool.shutdown();
    }
}

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-SoO1Ezcx-1579317893064)(assets/1579312076525.png)]

6. spring's multi-threaded approach

pom

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.2.RELEASE</version>
  </dependency>

Config

@Configurable
@ComponentScan("com.hfl.demo.liquidbasedemo.quartz")
@EnableAsync
public class Config  implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {//Implement the AsyncConfigurer interface, override the getAsyncExecutor method, and return a ThreadPoolTaskExecutor, so we get a TaskExecutor based on the thread pool
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);
        taskExecutor.setMaxPoolSize(80);
        taskExecutor.setQueueCapacity(100);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

DemoService

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class DemoService {

    @Async
    public void a(){
        while(true){
            System.out.println("implement a Method");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    @Async
    public void b(){
        while(true){
            System.out.println("implement b Method");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Test

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);
        DemoService ds = ac.getBean(DemoService.class);
        ds.a();
        ds.b();
    }
}

Run result: Loop execution

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-ypsIp84j-1579317893065)(.../.../java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E4%B8%8E%E5%AE%9E%E6%88%98/03/assets/1579314367736.png)]

7. Use lambd expressions

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-SNC2D2dJ-1579317893066)(assets/1579317694409.png)]

Divide sequential streams into blocks, then execute the results in parallel.The keyword is parallelStream:

Demonstration:

/**
 * Code concise
 * Concurrent support
 */
public class Demo7 {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(19,34, 56, 34);
        numbers.parallelStream().forEach(System.out::println);
    }
}

Run result:

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-BlYE9kMf-1579317893066)(assets/1579317801670.png)]

finish

213 original articles were published, 22 were praised, 60,000 visits+
Private letter follow

Tags: jvm Spring Java less

Posted on Fri, 17 Jan 2020 22:49:09 -0500 by Jnerocorp