Home >Java >javaTutorial >How to use Runnable interface in java

How to use Runnable interface in java

PHPz
PHPzforward
2023-05-02 20:34:061902browse

Explanation

1. Runnable is an interface that provides threads and has an abstract publicabstract void run() method.

2. To implement the class of this interface, its run method must be implemented.

In Runnable, there is no start method to start Runnable multi-threading through the Thread class.

Runnable can use the same object instance and share resources, but Thread cannot.

Example

public class Runnable implements Runnable{
    public void run() {
       public void run() {
           for (int i = 0; i < 60; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
           }
   }
}
}
public class Demo{
    public static void main(String[] args) {
        RunnableDemo run = new RunnableDemo();
        Thread t1 = new Thread(run);
        Thread t2 = new Thread(run);
        t1.start();
        t2.start();
    }
}

The above is the detailed content of How to use Runnable interface in java. For more information, please follow other related articles on the PHP Chinese website!

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