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

How to use Runnable interface to create thread in Java?

WBOY
Release: 2023-05-09 20:16:06
forward
1630 people have browsed it

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

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!

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