This is a simple interview question:
Write a simple example of a single and multi-threaded combination;
Code:
Single-Case Code:
Public classSingleton {Private inti = 0; //instantiating a singleton inside a class will load the static instance when the virtual machine starts the load class Private StaticSingleton Singleton =NewSingleton (); //liberalize constructors to ensure that external classes are not instantiated PrivateSingleton () {System.out.println ("Initialize a single case!"); } //gets the inner static instance method of the class Public StaticSingleton Getsingleton () {returnSingleton; } Public intGeti () {returni; } Public voidSetI (inti) { This. i =i; }}
Thread-Inheriting classes:
Public classMyThreadextendsThread {PrivateSingleton Singleton; //Construction MethodMyThread (Singleton Singleton) { This. Singleton =Singleton; System.out.println ("Initialize Thread!"); } @Override Public voidrun () {Super. Run (); Singleton.seti (Singleton.geti ()+ 1); System.out.println (Singleton.geti ()); }}
Test class:
Public classRun { Public Static voidMain (string[] args) {Singleton Singleton=Singleton.getsingleton (); //Build Thread Instance-1MyThread Thread1 =NewMyThread (singleton); //Build Thread Instance-2MyThread thread2 =NewMyThread (singleton); //Build Thread Instance-3MyThread thread3 =NewMyThread (singleton); //Build Thread Instance-4MyThread thread4 =NewMyThread (singleton); //Start thread-1Thread1.start (); //Start Thread-2Thread2.start (); //Start Thread-3Thread3.start (); //Start Thread-4Thread4.start (); }}
Test class Output:
Initialize a single case! Initialize the thread ! Initialize the thread ! Initialize the thread ! Initialize thread !1234
Analysis:
1. Here we see that the singleton is instantiated only once, which is the characteristic of the singleton pattern, and multiple threads are shared with singleton instances;
2. Inheriting thread is one of the simple methods of multithreading implementation, but because Java is a single inheritance, if it is already inheriting classes of other classes, then it can be implemented by implementing the Runnable interface;
Simple multithreading and single case study one