JavaEE____ Multithreading 1

1. Thread usage

1. Thread sleep demo print movie subtitles

/*
* 使用线程实现电影旁白的打印
* */
public class ThreadDemo1 {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        String content = "想把我唱给你听,趁现在年少如花";
        for (char item : content.toCharArray()){
    
    
            System.out.print(item);
            Thread.sleep(250);
        }

    }
}

2. Multi-threaded performance vs single-threaded performance

2.1 Single thread execution time

public class ThreadDemo2 {
    
    
    private final static  int COUNT = 10;
    public static void main(String[] args) {
    
    
        //记录开始时间
        long stime = System.currentTimeMillis();

        //使用单线程执行
        singleThread();

        //记录结束时间
        long etime = System.currentTimeMillis();
        System.out.println("单线程执行时间:" + (etime - stime));
    }

    /*
    * 单线程任务执行
    * */
    private static void singleThread(){
    
    

        for (int i = 0; i < COUNT ; i++) {
    
    
            //每次方法执行需要一秒
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }

}

insert image description here

2.2 Multi-thread execution time

3. 3 ways to create threads

3.1 Creation Method 1: Inheriting Thread

/*
* 继承Thread 创建线程
*/
public class ThreadDemo3 {
    
    
    public static void main(String[] args) {
    
    
        //获得当前的线程
        Thread mainThread = Thread.currentThread();
        System.out.println("线程名称" + mainThread.getName());


        Thread thread = new MyThread();
        //开启线程
        thread.start();
    }
}
class MyThread extends Thread{
    
    
    @Override
    public void run() {
    
    
        //具体业务执行代码
        Thread thread = Thread.currentThread();
        System.out.println("线程的名称" + thread.getName());
    }
}


insert image description here

a) Watch the thread with jconsole

b) Start the thread - start method

 thread.start();

Earlier we saw how to create a thread object by overriding the run method, but the creation of the thread object does not mean that the thread starts running
1) Overriding the run method is a list of instructions provided to the thread for what to do
2) The thread object can be considered as calling Li Si and Wang Wu over
3) When calling the start() method, it is just shouting: "Go!", and the thread is executed in an independent area.

Execute the run method:
insert image description here
execute the start method
insert image description here
Difference 1: The start method will create a new thread, the run method just uses the main method to call a common method
Difference 2: The run method is also called the thread body, which contains the specific business code to be executed. When the run method is called, the code in the run method is executed immediately (if the current thread time slice is not used up);
when the start method is called, a thread is started and the state of the thread is set to the ready state. That is to say, calling the start method will not execute immediately.

Difference 3: The run method can be called multiple times, while the start method can only be called once.

Inheriting Thread and creating a new thread Disadvantages:
Java language is single inheritance, if you inherit Thread, you cannot inherit other classes

3.2 Creation method 2: Implement the Runnable interface (4 ways of writing)

3.2.1 Writing method 1

/*
* 实现Runnable 接口新建线程
* */
public class ThreadDemo4 {
    
    
    public static void main(String[] args) {
    
    
       //创建Runnable
        MyThread2 myThread2 = new MyThread2();
        //创建一个线程
        Thread thread = new Thread(new MyThread2());
        //启动线程
        thread.start();

    }
}
class MyThread2 implements  Runnable{
    
    

    @Override
    public void run() {
    
    
        //具体业务代码
        Thread thread = Thread.currentThread();
        System.out.println("线程执行" + thread.getName());
    }
}

insert image description here

3.2.2 Writing method 2

/*
* Runnable 匿名内部类来创建
**/
public class ThreadDemo5 {
    
    
    public static void main(String[] args) {
    
    

        //匿名内部类
        Thread thread = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                //具体的业务代码
                Thread t = Thread.currentThread();
                System.out.println("执行任务:" + t.getName());
            }
        });
        //启动线程
        thread.start();
    }
    }

insert image description here

3.2.3 Writing method 3

*
* 使用Lambda 来创建线程
* */
public class ThreadDemo6 {
    
    
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(() -> {
    
    
            //具体的业务
            Thread t = Thread.currentThread();
            System.out.println("任务执行" + t.getName());
        });

        //启动线程
        thread.start();
    }
}

insert image description here

3.2.4 Writing method 4

public class ThreadDemo7 {
    
    
    public static void main(String[] args) {
    
    
        //创建线程并初始化
        Thread thread = new Thread(){
    
    
            @Override
            public void run() {
    
    
                Thread t = Thread.currentThread();
                System.out.println("任务执行" + t.getName());
            }
        };
        //启动线程
        thread.start();
    }
}

insert image description here
Problem:
The above methods of creating threads have a common problem, that is, there is no return value, that is to say, when the thread execution is completed, the main thread has no way to get the execution result of the new thread.

3.3 Creation method 3: Implement the Callable interface for implementation (2 ways of writing)

3.3.1 Callable+Future

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class ThreadDemo8 {
    
    
    public static void main(String[] args)  throws ExecutionException,InterruptedException{
    
    
        //创建Callable实例
        MyCallable myCallable = new MyCallable();
        //用于接受Callable结果的对象
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
        //创建新线程
        Thread thread = new Thread(futureTask);
         //启动线程
        thread.start();

        int result = futureTask.get();
        System.out.println(Thread.currentThread().getName() + "新线程返回的结果为:" + result);
    }
}
//Callable<可以是任意数据类型>
class MyCallable implements Callable<Integer>{
    
    

    @Override
    public Integer call() throws Exception {
    
    
        //生成随机数 0-9
        int randomNum = new Random().nextInt(10);
        System.out.println(Thread.currentThread().getName()+"--随机数:" + randomNum);
        return randomNum;

    }
}

insert image description here

3.3.2

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadDemo9 {
    
    
    public static void main(String[] args) throws ExecutionException,InterruptedException {
    
    

        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
    
    
            @Override
            public String call() throws Exception {
    
    
               //新线程执行的业务代码
                String[] arrs = new String[]{
    
    "Java","MySQL","Thread"};
                String result = arrs[new Random().nextInt(3)];
                System.out.println(Thread.currentThread().getName() + "--字符串" + result);
                return null;
            }
        });
        Thread thread = new Thread(futureTask);

        thread.start();
        String result = futureTask.get();
        System.out.println(Thread.currentThread().getName() + "--新线程的返回值" + result);
    }
}

![在这里插入图片描述](https://img-blog.csdnimg.cn/75f28e9776be4dd8bc7c0bc3ce1c59c5.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5ryr5aSpIOaYn-i-sA==,size_20,color_FFFFFF,t_70,g_se,x_16)


Guess you like

Origin blog.csdn.net/biteqq/article/details/123630367