Java multithreading study notes (1) three ways to create threads

Multithreading:
    Refers to multiple threads that execute concurrently in an application. Each thread is called a thread. They execute alternately and can communicate with each other.
Thread:
    In the computers we use in our lives, every program running in the computer is actually a process. There can also be multiple execution units running at the same time in a process, and these units can be regarded as a clue of program execution. , Is called a thread. At least one thread is running in each given process.
Thread realization method: The
    first type : realize multi-threading by inheriting Thread class
Example:

public class Example01 {
    
    
    public static void main(String[] args) {
    
    
        MyThread myThread = new MyThread();//创建线程MyThread的线程对象
        myThread.start();//开启线程
        for (int i = 0; i <= 5; i++){
    
    
            System.out.println("main()方法:" + i + "在运行");
        }
    }
}
//MyThread继承Thread类
class MyThread extends Thread{
    
    
    //重写父类的run()方法
    @Override
    public void run() {
    
    
        for(int i = 0; i <= 5; i++){
    
    
            System.out.println("MyThread的run()方法:" + i + "正在运行");
        }
    }
}

Running results:
Insert picture description hereAs can be seen from the above results, the output statements of the two methods are executed alternately, which realizes multithreading. The difference between single-threaded and multi-threaded is that single-threaded is executed sequentially, while multiple threads can run at the same time without affecting each other.
    The second type : multithreading by implementing the Runnable interface.
Examples:

public class Example02 {
    
    
    public static void main(String[] args) {
    
    
        //创建RunnableDemo类的实例对象
        RunnableDemo runnableDemo = new RunnableDemo();
        //创建线程对象
        Thread thread = new Thread(runnableDemo);
        //开启线程,执行线程的run()方法
        thread.start();
        for (int i = 0;i <= 5; i++ ){
    
    
            System.out.println("mian方法在" + i + "在运行" );
        }
    }
}
//RunnableDemo类实现Runnable接口
class RunnableDemo implements Runnable{
    
    
    //当线程调用了start()方法时,该方法就会执行
    public void run() {
    
    
        for (int i = 0;i <= 5; i++ ){
    
    
            System.out.println("RunnableDemo类的run()方法:" + i + "在运行" );
        }
    }
}

Running result: Insert picture description here
    The limitation of singleness in Java inheritance will have the Runnable interface to realize multithreading. In order to overcome the drawbacks, the Thread class provides another construction method Thread (Runnable r). Among them, Runnable is an interface, it has only one method run() method. When creating a thread object through the Thread(Runnable r) construction method, we only need to pass an instance object that implements the Runnable interface to the method, so that the created thread will call the run() method that implements the Runnable interface to run the most code. There is no need to call the run() method in the Thread class.
    The third type : realize multithreading by implementing the Callable interface.
Examples:

public class Example03 {
    
    
    public static void main(String[] args)throws Exception{
    
    
        MyCallable callable = new MyCallable();//实例化MyCallable类的实例
        FutureTask<String> task = new FutureTask<String>(callable);
        new Thread(task).start();//启动线程
        String s = task.get();//获得返回值
        System.out.println(s);//输出结果
    }
}
//MyCallable实现Callable接口
class MyCallable implements Callable<String>{
    
    
    public String call() throws Exception {
    
    
        for (int i = 0;i <= 5; i++ ){
    
    
            System.out.println("MyCallable类的call()方法在" + i + "在运行" );
        }
        return "MyCallable执行完毕";
    }
}

    The difference between the Thread class and the Runnable interface:
Take an example, for example, a station has two ticket windows, and tickets for the same train number are sold at the same time. Look at the effect through two examples of the Thread class and the Runnable interface.
example 1:

public class Example04 {
    
    
    public static void main(String[] args) {
    
    
        //创建一个线程对象
        BusTicket busTicket1 = new BusTicket();
        //为线程设置一个名称
        busTicket1.setName("窗口1");
        //开启该线程
        busTicket1.start();
        BusTicket busTicket2 = new BusTicket();
        busTicket2.setName("窗口2");
        busTicket2.start();
    }
}
class BusTicket extends Thread{
    
    
    private int ticket = 64;//车票数量
    @Override
    public void run() {
    
    
        int a = 0;
        while (a <= 64 ){
    
    
            a++;
            if (ticket > 0 ){
    
    
                //获取当前线程
                Thread thread = Thread.currentThread();
                //获取线程的名字
                String threadName = thread.getName();
                System.out.println(threadName + "正在发第" + ticket-- + "张票");
            }
        }
    }
}

Operation result:
Insert picture description here
    As can be seen from the above operation result, because it is impossible to sell two tickets for one ticket at the same time, it is obvious that this result is incorrect. That is, resources are not shared. We can only create a ticketing object in the program, and open multiple threads to execute the ticketing method in the ticketing at the same time. In other words, if multiple threads run the same ticketing program, the Runnable interface in multiple threads will be used.
Example 2:

public class Example05 {
    
    
    public static void main(String[] args) {
    
    
        //创建线程对象
        BusTicket2 busTicket = new BusTicket2();
        //启动线程并为线程设置名字
        new Thread(busTicket,"窗口1").start();
        new Thread(busTicket,"窗口2").start();
    }
}
class BusTicket2 implements Runnable{
    
    
    private int ticket = 64;//车票数量
    public void run() {
    
    
        int a = 0;
        while (a <= 64 ) {
    
    
            a++;
            if (ticket > 0 ){
    
    
                //获取当前线程
                Thread thread = Thread.currentThread();
                //获取线程的名字
                String threadName = thread.getName();
                System.out.println(threadName + "正在发第" + ticket-- + "张票");
            }
        }
    }
}

Example:
Insert picture description here
    Create a thread object, open two threads to call the ticketing method, so as to ensure that multiple threads access the same resource.
Come on! ! !

Guess you like

Origin blog.csdn.net/qq_42494654/article/details/109370174