Java multithreaded programming USES the runnable interface to create threads

  • 2020-04-01 02:50:35
  • OfStack

1. Instantiate the class that implements the Runnable interface.

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

Finally, a Thread is created through the start method of the Thread class.
The following code demonstrates how to create threads using the Runnable interface:

Package mythread;
Public class MyRunnable implements Runnable
{
  Public void the run ()
  {
  System. Out. Println (Thread. CurrentThread (). The 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);
  MyThread2 thread2. Elegantly-named setName (" ");
  Thread1. Start ();
  Thread2. Start ();
  }
}
[/ code]
The result of the above code is as follows:


MyThread1
MyThread2


Related articles: