Home  >  Article  >  Java  >  Implement java threads by inheriting the Thread class

Implement java threads by inheriting the Thread class

王林
王林forward
2020-05-30 16:28:174128browse

Implement java threads by inheriting the Thread class

The Thread class is the parent class of all thread classes and implements the extraction and encapsulation of threads.

The specific steps to inherit the Thread class to create and start multi-threads are:

1. Define a class, inherit from the Thread class, and override the run method of the class, and the method of the run method The body represents the task that the thread needs to complete. Therefore, the method body of the run method is called the thread execution body.

2. Create an object of Thread subclass, that is, create a child thread.

3. Use the start method of the thread object to start the thread.

(Video tutorial recommendation: java video)

Example:

Demo first creates a ticket sales thread

package demo1;

public class SellTickets extends Thread {
    //共享数据
    static int count = 100;
    @Override
    public void run() {
        //循环售票
        while(count > 0) {
            count--;
            System.out.println(Thread.currentThread().getName() + "售出了一张票,剩余" + count);
        }
    }
}

Test class

import demo1.SellTickets;

public class TheadDemo {

    public  static void main(String[] args) {
        //模拟四个售票员售票
        SellTickets s1 = new SellTickets();
        SellTickets s2 = new SellTickets();
        SellTickets s3 = new SellTickets();
       // System.out.println(s1.currentThread().getName());  //这个线程的名称是main
        s1.start();
        s2.start();
        s3.start();

    }
}

Test results:

Implement java threads by inheriting the Thread class

Recommended tutorial: java entry program

The above is the detailed content of Implement java threads by inheriting the Thread class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete