In this chapter we discuss the use of constructors or internal classes to implement multi-threaded coding variants.
1. Basic implementation
Package Com.ray.ch17;public class Test {public static void main (string[] args) {Thread thread1 = new Extendsthread (); Threa D1.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. Using the constructor to hide the start of the thread
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 inner classes to hide multi-threaded 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 variants.
This chapter is here, thank you.
-----------------------------------
Directory
Understanding java-18.2 Basic threading mechanism from the beginning (6)-using constructors or internal classes to implement multithreaded encoding variants