• A program is a static concept.
  • A process is a dynamic execution of a program. A unit of system resource allocation.
  • A process can contain several threads, which are the unit of CPU scheduling and execution. Is an independent execution path.

Under the premise of only one CPU, the CPU can only execute one code at a time, because the switching speed is fast, so there will be the illusion of simultaneous execution.

Threads do not necessarily execute immediately and are scheduled by the CPU.

Various ways to create threads

  1. Thread class inheritance
  2. Implement the Runnable interface
  3. Implement Callable interface

1. Inherit the Thread class

/** * 1. Use Thread -> to override the run method
class Thread1 extends Thread {

    @Override
    public void run(a) {
        System.out.println("1. Inherit Thread class -> override run method: + this.getName()); }}Copy the code
// Start the thread
// 1. Inherit Thread
Thread thread1 = new Thread1();
thread1.start();
/ / or
// Thread1 tt = new Thread1();
// tt.start();
Copy the code

2. Implement Runnable methods

Avoid single inheritance limitations

/** * 2. Implement Runnable interface -> override the run method */
class Thread2 implements Runnable {
    @Override
    public void run(a) {
        System.out.println(2. Implement the Runnable interface -> override the run method:+ Thread.currentThread().getName()); }}Copy the code
2. Implement the Runnable interface
Thread2 runnable = new Thread2();
Thread thread2 = new Thread(runnable);
thread2.start();
Copy the code

3. Implement the Callable interface

The return value type is required

Rewrite call() to throw an exception

/** * 3. Implement Callable interface -> override call method */
class Thread3 implements Callable<String> {
    @Override
    public String call(a) throws Exception {
        System.out.println("3. Implement Callable interface -> override call method:" + Thread.currentThread().getName());
        return "Call () returns parameters"; }}Copy the code
// 3. Implement Callable interface
FutureTask<String> futureTask = new FutureTask<>(new Thread3());
new Thread(futureTask).start();
// An exception needs to be caught
System.out.println(futureTask.get());
Copy the code