Understanding the basic thread mechanism of java-18.2 from the ground up (6)-using constructors or internal classes to implement multi-thread coding variations
In this section, we will discuss how to use constructors or internal classes to implement multi-threaded coding variations.
1. Basic implementation
package com.ray.ch17;public class Test {public static void main(String[] args) {Thread thread1 = new ExtendsThread();thread1.start();Thread thread2 = new Thread(new ImplRunnable());thread2.start();}}class ExtendsThread extends Thread {@Overridepublic void run() {System.out.println("ExtendsThread");}}class ImplRunnable implements Runnable {@Overridepublic void run() {System.out.println("ImplRunnable");}}
Output:
ExtendsThread
ImplRunnable
2. Use the constructor to hide the Thread startup
package com.ray.ch17;public class Test {public static void main(String[] args) {new ExtendsThread();new ImplRunnable();}}class ExtendsThread extends Thread {public ExtendsThread() {start();}@Overridepublic void run() {System.out.println("ExtendsThread");}}class ImplRunnable implements Runnable {public ImplRunnable() {new Thread(this).start();}@Overridepublic void run() {System.out.println("ImplRunnable");}}
Output:
ExtendsThread
ImplRunnable
3. Use internal classes to hide multi-thread extensions
package com.ray.ch17;public class Test {public static void main(String[] args) {new ExtendsThread();new ImplRunnable();}}class ExtendsThread {public ExtendsThread() {new Inner();}private class Inner extends Thread {public Inner() {start();}@Overridepublic void run() {System.out.println("ExtendsThread");}}}class ImplRunnable {public ImplRunnable() {new Inner();}private class Inner implements Runnable {public Inner() {new Thread(this).start();}@Overridepublic void run() {System.out.println("ImplRunnable");}}}
Output:
ExtendsThread
ImplRunnable
Summary: This chapter mainly discusses the use of constructors or internal classes to implement multi-threaded coding variations.