Home > Java > Javagetting Started > body text

Implement java threads by inheriting the Thread class

王林
Release: 2020-05-30 16:28:17
forward
4129 people have browsed it

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);
        }
    }
}
Copy after login

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();

    }
}
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template