Home > Java > javaTutorial > body text

Java thread method to create thread using Runnable interface

黄舟
Release: 2016-12-19 14:33:40
Original
1793 people have browsed it

Classes that implement the Runnable interface must use an instance of the Thread class to create a thread. Creating a thread through the Runnable interface is divided into two steps:

1. Instantiate the class that implements the Runnable interface.

2. Create a Thread object and pass the object instantiated in the first step as a parameter to the constructor of the Thread class.

Finally, create the thread through the start method of the Thread class.

The following code demonstrates how to use the Runnable interface to create a thread:

package mythread;

 public class MyRunnable implements Runnable
 {
     public void run()
     {
         System.out.println(Thread.currentThread().getName());
     }
     public static void main(String[] args)
     {
         MyRunnable t1 = new MyRunnable();
         MyRunnable t2 = new MyRunnable();
         Thread thread1 = new Thread(t1, "MyThread1");
         Thread thread2 = new Thread(t2);
         thread2.setName("MyThread2");
         thread1.start();
         thread2.start();
     }
 }
Copy after login

The running results of the above code are as follows:

MyThread1
MyThread2
Copy after login


source:php.cn
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