Use polymorphic mechanism to create subclass object of thread Thread1 and overwrite the parent class's Run method
Thread thread = new Thread () {}
The concept of polymorphism thread is a subclass of Thrad
The Thread calls run () after Start (), and the Run method first determines if there is a runable parameter and then calls Runable.run () No other code is executed down
If the subclass is covered with run () then it will not go to the run () that runable directly executes the subclass.
At this point the object can start the thread directly using the Start method
Thread thread1=new Thread() { public void run() { while(true) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(this.getName()); } } }; thread1.start();
Or
package thread;public class demo_1 { public static void main(String[] args) { cat c=new cat(); c.start(); }}class cat extends Thread{ public void run() { while(true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("11111"); } }}
If you implement the Runable interface, you need to pass the object to thread
Object can call the run startup thread
Dog D=new Dog ();
Thread t=new thread (d);
D.run ();
That overrides the class D that implements the Ruable
Equivalent to the thread t=new thread (new Dog (). run ());
package thread;public class demo_2 { public static void main(String[] args) { dog d=new dog(); Thread t=new Thread(d); d.run(); }}class dog implements Runnable{ public void run() { while(true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("11111"); } }}
To create a threading method