Threads in Java

1. Processes and threads

A process refers to an application running in memory, each process has its own independent memory space, and a process can start multiple threads. For example, in Windows system, a running exe is a process.

A thread refers to an execution flow in a process, and a process can run multiple threads. For example, the java.exe process can run many threads. A thread always belongs to a process, and multiple threads in a process share the memory of the process.

Second, the creation of Java threads

    1. Inherit the Thread class

Thread t = new Thread(){
    @Override
public void run() {
        for (int i=0;i<10;i++){    
            System.out.println(getName()+i);
        }
    }
};

   2. Implement the Runnable interface or the Callable interface

Thread t2 = new Thread(new Runnable() {
    @Override
public void run() {
        for (int i=0;i<10;i++){    
            System.out.println(i);
        }
    }
});

Third, the start of the thread

    Instead of calling the run method, call the start method on the thread object.

    After calling the start method, the thread enters the runnable state. When the thread is allocated CPU resources, its target method run method will run.

Summarize:

        1. Inheriting from the Thread class, you can use the methods of the Thread class, but the scalability is not good, because Java is single inheritance.

        2. Implement the Runnable interface, with good scalability

    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325667288&siteId=291194637