The so-called thread, is a simple process, multi-threaded can achieve a number of operations, so as to enrich my function.
Threads have the following states:
Operational state, running state, blocking state, destroying state.
There are generally two ways to run a thread, one is to inherit the thread class and override the Run method. The second is to write runnable and then rewrite the run method to implement the thread.
Here are two different methods:
1:
Package Test;public class Dxcheng {/** * @param args */public static void main (string[] args) {//TODO auto-generated Meth OD stubCat1 cat1=new Cat1 ();//start thread, enable Run function, go to operational status Cat1.start ();}} Class CAT1 extends Thread{int times=0;public void Run () {while (true) {//Hibernate 1000 milliseconds try {//Enter blocking state thread.sleep (+);} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Hello" +times); Times++;if (times==10) {//exit thread break;}}}
2:
Package Test;public class Runnable {/** * @param args */public static void main (string[] args) {//TODO auto-generated met Hod stubdogs dog1=new Dogs (); Thread t=new thread (DOG1); T.start ();}} Class Dogs implements Runnable{int Times=0;public void Run () {while (true) {try {thread.sleep (+); times++;} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Hello" +times); if (times==10) {break;}}}}
The end is to implement multi-threaded alternating work:
Package Test;public class Runnable {/** * @param args */public static void main (string[] args) {//TODO auto-generated met Hod stubdogs dog1=new Dogs (); Thread t=new thread (DOG1); Pig pig1=new Pig (); Thread m=new thread (PIG1); T.start (); M.start ();}} Class Dogs implements Runnable{int Times=0;public void Run () {while (true) {try {thread.sleep (+); times++;} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("I Am a Dog" +times); if (times==10) {break;}}}} Class Pig implements Runnable{int Times=0;public void Run () {while (true) {try {thread.sleep]; times++;} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("I Am a pig:" +times); if (times==10) {break;}}}}
Basic understanding and operating mechanism of multi-threading in Java