Threads and processes

Processes are the smallest unit of resource allocation and threads are the smallest unit of CPU scheduling

  • A thread moves under a process
  • A process can contain multiple threads
  • Data is difficult to share between different processes
  • Data is easily shared between threads in the same process

How threads are created

Inheriting the Thread class

1. Define a class that inherits the Thread class and overrides the run method

public class MyThread extends Thread {
    @Override
    public void run(a) {
        System.out.println("I inherit Thread."); }}Copy the code

2. Start a new Thread by calling the start method in the Thread class

Note: What is the difference between calling the run method directly and the start method?

  • You can call the run method directly, but you don’t start a separate thread;
  • Calling the start method opens a separate new thread and calls the run method;
public static void main(String[] args) {
    System.out.println("111111");
    MyThread t1 = new MyThread();
    t1.start();
    System.out.println("22222");
}
Copy the code

The result is that the run method of thread T1, which prints the statement before executing the main statement, is two different threads


Implement the Runnable interface mode

1. Define a custom class that implements the Runnable interface and overwrites the Run method

public class MyThread2 implements Runnable{
    @Override
    public void run(a) {
        System.out.println("I'm a class that implements the Runnable interface..."); }}Copy the code

2. Invoke the Thread(Runnable target) method to create a Thread object

public static void main(String[] args) {
    System.out.println("111111");
    Thread t2 = new Thread(new MyThread2());
    t2.start();
    System.out.println("22222");
}
Copy the code

Results:


If the thread is used once, you can also use anonymous inner classes

public static void main(String[] args) {
    System.out.println("111111");
    Thread t3 = new Thread(new Runnable() {
        @Override
        public void run(a) {
            System.out.println("I'm anonymous inner class."); }}); t3.start(); System.out.println("22222");
}
Copy the code

Result: Same effect