Thread creation methods and advantages and disadvantages

 

 

1 How to create:

 

The core method run in Thread, see the following code to know, 1 can override this method after inheriting the Thread class. You can also pass the Runnable class in public Thread(Runnable target) when it is created and implement the run() method of Runnable in these two ways
Implement inheritance Thread class
 @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

 

Among them, Java is a single-base multi-implementation system. If we use the extends Thread method, if our class already inherits a class, we cannot extend the Thread class, and we can use the static proxy class method to achieve thread creation and share resources. (See how to share resources

The use of thread static proxy  simulates ticket grabbing code)

Therefore it is recommended to use the second method:

public Thread(Runnable target) Pass the Runnable class at creation time and implement Runnable's run() method

 

2 Create threads by inheritance:

 

/**
 * Simulate tortoise and hare race
 1. Create multi-thread inheritance Thread + rewrite run (thread body)
 2. Use thread: create subclass object + object.start() thread start
     
 *
 * @author Administrator
 *
 */
public class Rabbit extends Thread {

	@Override
	public void run() {
		// thread body
		for(int i=0;i<100;i++){
			System.out.println("The rabbit ran "+i+" step");
		}
		
		
	}
	
}
class Tortoise extends Thread {

	@Override
	public void run() {
		// thread body
		for(int i=0;i<100;i++){
			System.out.println("The turtle ran "+i+" step");
		}
		
		
	}
	
}


public class RabbitApp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//create subclass object
		Rabbit rab = new Rabbit();
		Tortoise tor =new Tortoise();
		
		
		//Call the start method to start the rabbit thread
		rab.start(); //Do not call the run method, it is equivalent to the thread is ready, join the thread group, and inform the cpu. The time slice waiting for the CPU to allocate computing resources (the rabbit is ready at the starting line, waiting for the referee to fire)
		//Call the start method to start the turtle thread
		tor.start();
		// start a loop in the main thread so that after the process RabbitApp starts, there will be three threads in it. After execution, you can see that only this thread is executing and printing the result in the time slice where each line in the execution result is located.
		for(int i=0;i<1000;i++){
			System.out.println("main==>"+i);
		}
	}

}

 

 

 

 For the second creation method, see: 

The use of thread static proxy 

 

Guess you like

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