First, inherit the implementation of multi-threading
Rabit.java
Package cn.thread; / * * analog Hare * 1. Create Thread + inheritance weight multithreaded run (thread body) * / public class Rabit the extends the Thread { @Override public void run () { for ( int I = 0; I <100; I ++ ) { System.out.println ( "rabbit run" + i + "step" ); } } } class Tortoise the extends the Thread { @Override public void rUN () { for ( int I = 0; I < 100; I ++ ) { System.out.println ( "tortoise ran" + i + "step" ); } } }
RabitApp.java
Package cn.thread; public class RabitApp { public static void main (String [] args) { // 1. Create a subclass object Rabit RAB = new new Rabit (); Tortoise Tor = new new Tortoise (); // 2. call start () method rab.start (); tor.start (); for ( int I = 0; I <1000; I ++ ) { System.out.println ( "main -" + I); } } }
effect
Two, Runnable interface to achieve multi-threaded
Compared with the inheritance:
1. static agent (StaticProxy)
StaticProxy.java
Package cn.thread; / * * static proxy design pattern * 1, the real role of * 2, holds true agent roles reference character * 3, both implement the same interface * / public class StaticProxy { public static void main (String [ ] args) { // create a real role you = the y- new new you (); // create a proxy role WeddingCompany Company = new new WeddingCompany (the y-); Company.marry (); } } // Interface interface Marry { public abstract void Marry ( ); } //Real character class you the implements Marry { @Override public void Marry () { System.out.println ( "married" ); } } // proxy role class WeddingCompany the implements Marry { Private Marry you; public WeddingCompany () { } public WeddingCompany (Marry you) { the this .You = you; } Private void before () { System.out.println ( "disposed pigsties ..." ); } Private void after() { System.out.println("收拾猪窝.。。。"); } @Override public void marry() { before(); you.marry(); after(); } }
effect: