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

How to use Runnable interface in java

PHPz
Release: 2023-05-02 20:34:06
forward
1946 people have browsed it

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

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!

Related labels:
source:yisu.com
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