This article mainly introduces java RunnableInterfaceRelated information on creating threads, friends in need can refer to it
java Runnable interface creates threads
The simplest way to create a thread is to create a class that implements the Runnable interface.
In order to implement Runnable, a class only needs to execute a method calling run(), declared as follows:
public void run()
You can override this method, the important thing is to understand run() You can call other methods, use other classes, and declare variables just like the main thread.
After creating a class that implements the Runnable interface, you can instantiate a thread object in the class.
Thread defines several construction methods, the following one is what we often use:
Thread(Runnable threadOb,String threadName);
Here, threadOb is a class that implements the Runnable interface instance, and threadName specifies the name of the new thread.
After a new thread is created, it will not run until you call its start() method.
void start();
Example
The following is an example of creating a thread and starting it to execute:
// 创建一个新的线程 class NewThread implements Runnable { Thread t; NewThread() { // 创建第二个新线程 t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // 开始线程 } // 第二个线程入口 public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); // 暂停线程 Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } public class ThreadDemo { public static void main(String args[]) { new NewThread(); // 创建一个新线程 try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(100); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }
The results of compiling the above program are as follows:
Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.
The above is the detailed content of Detailed explanation of Java's Runnable interface to create threads. For more information, please follow other related articles on the PHP Chinese website!