Home  >  Article  >  Java  >  How to use Runnable interface to create thread in Java?

How to use Runnable interface to create thread in Java?

WBOY
WBOYforward
2023-05-09 20:16:061552browse

1. Description

You need to implement the run() method of the Runnable interface. When using newThread(newRunableClass() to generate a thread object (RunnableClass has implemented the Runnable interface), the run of the thread object () method calls run() of RunnableClass.

2, instance

package com.java.test;
 
public class ThreadTest
{
    public static void main(String[] args)
    {
//         线程的另一种实现方法,也可以使用匿名的内部类
        Thread threadtest1=new Thread((new ThreadTest1()));
        threadtest1.start();
        Thread threadtest2=new Thread((new ThreadTest2()));
        threadtest2.start();
    }
}
 
class ThreadTest1 implements Runnable
{
 
    @Override
    public void run()
    {
        for (int i = 0; i < 100; ++i)
        {
            System.out.println("Hello: " + i);
        }
    }
}
 
class ThreadTest2 implements Runnable
{
 
    @Override
    public void run()
    {
        for (int i = 0; i < 100; ++i)
        {
            System.out.println("Welcome: " + i);
        }
    }
}

The above is the detailed content of How to use Runnable interface to create thread 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