//Example: establishing and starting two threads Public classThreadTestImplementsrunnable{ Public Static voidMain (string[] args) {ThreadTest runner=NewThreadTest ();//Create an instance of RunnableThread alpha=NewThread (runner); Thread Beta=NewThread (runner);//Create two threads, using the same runnable, i.e. the same taskAlpha.setname ("Alpha thread")); Beta.setname ("Beta thread");//take a name for a threadAlpha.start (); Beta.start ();//Start Thread} @Override Public voidrun () { for(inti=0;i<25;i++) {String threadname=Thread.CurrentThread (). GetName (); System.out.println (ThreadName+ "" +i+ "is running"); } } }
Output Result:
Beta Thread 0 is running
Beta Thread 1 is running
Alpha Thread 0 is running
Alpha Thread 1 is running
Alpha Thread 2 is running
Alpha Thread 3 is running
Alpha Thread 4 is running
Alpha Thread 5 is running
Alpha Thread 6 is running
Alpha Thread 7 is running
Alpha Thread 8 is running
Alpha Thread 9 is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Alpha Thread is running
Beta Thread 2 is running
Beta Thread 3 is running
Beta Thread 4 is running
Beta Thread 5 is running
Beta Thread 6 is running
Beta Thread 7 is running
Beta Thread 8 is running
Beta Thread 9 is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
Beta Thread is running
//Example: Display Scheduler has multiple unpredictable resultsclassMyrunnableImplementsrunnable{@Override Public voidrun () {go (); } Public voidGo () {domore (); } Public voidDomore () {System.out.println ("Top O ' the stack"); }} Public classthreadtest2{ Public Static voidMain (string[] args) {Runnable threadjob=Newmyrunnable (); Thread MyThread=NewThread (threadjob); Mythread.start (); System.out.println ("Back in Main"); }}
Output Result:
Back in Main
Top O ' the stack
Or
Top O ' the stack
Back in Main
Multithreading-Example: establishing and starting two threads and examples: Display scheduler with multiple unpredictable results (Head first Java example)