Two ways to implement threading in Java
- Inherit the thread class
- Implementing the Runnable Interface
The differences between them are as follows:
1) Java classes are single-inheritance, but multiple interfaces can be implemented, so runnable may be more appropriate in some scenarios than thread
2) thread implements the Runnable interface, and there are more practical methods
3) threads are still dependent on thread startup when implementing Runnable interface
ImportJava.util.Map;ImportJava.util.concurrent.ConcurrentHashMap;ImportOrg.junit.Assert;Importorg.junit.Test;/*** @Description: Two ways to implement threading*/ Public classThreadimplementtest {PrivateMap<integer, long> map =NewConcurrenthashmap<>(); classMethodOneextendsThread {Private intCount = 0; @Override Public voidrun () {Map.put (++count, This. GetId ()); } } classMethodtwoImplementsRunnable {Private intCount = 0; @Override Public voidrun () {Map.put (++count, Thread.CurrentThread (). GetId ()); }} @Test Public voidTextthread () {/*** Method One: Inherit thread*/MethodOne Extendsthread=NewMethodOne (); Extendsthread.start (); /*** Method Two: Realize runnable*/methodtwo implementsrunnable=NewMethodtwo (); NewThread (implementsrunnable). Start (); } @Test Public voidTesttworuns ()throwsinterruptedexception {/*** Note: The following two methods start differently*/Thread tmp; MethodOne Extendsthread=NewMethodOne (); for(inti = 0; I < 3; i++) {//only one threadTMP =NewThread (Extendsthread); Tmp.start (); Tmp.join (); } assert.asserttrue (Map.containskey (3)); Assert.asserttrue (Map.containskey (2)); Assert.asserttrue (Map.containskey (1)); Map.clear ();//Empty Cache for(inti = 0; I < 3; i++) {//three different threadsTMP =NewMethodOne (); Tmp.start (); Tmp.join (); } assert.assertequals (1, Map.size ()); Assert.asserttrue (Map.containskey (1)); }}
Java Multithreaded Series one--java implementing threading methods