A thread is a single sequential control flow in a program. A relatively independent, scheduled execution unit within a process is the unit of dispatch for the system to dispatch and dispatch CPUs independently of the operating program. Running multiple threads at the same time in a single program accomplishes different tasks, called multithreading.
Process is a computer program on a data set on a running activity, the system is the basic unit of resource allocation and scheduling, is the basis of the operating system structure.
Java threads are created in two ways:
1. Inheriting the thread class
Public classMyThreadextendsthread{PrivateString name; PublicMyThread (String name) { This. Name =name; } Public voidrun () {Try { for(inti = 0; I < 5; i++) {Thread.Sleep (100);//increase code Execution timeSystem.out.println ("Thread" + This. Name + ":" +i); } } Catch(interruptedexception e) {e.printstacktrace (); } } Public Static voidMain (string[] args) {Thread thread1=NewMyThread ("One"); Thread thread2=NewMyThread ("the"); Thread1.start (); Thread2.start (); }}
Output Result:
Thread one:0threadone: 0thread: 1thread One:1thread one:2thread one: 2Thread One:3threadone: 3thread One:4Thread:4
2. Implement Interface runnable
1 Public classMyThread2ImplementsRunnable2 {3 PrivateString name;4 5 PublicMyThread2 (String name)6 {7 This. Name =name;8 }9 Ten Public voidRun () One { A Try - { - for(inti = 0; I < 5; i++) the { -Thread.Sleep (100);//increase code Execution time -System.out.println ("Thread" + This. Name + ":" +i); - } + } - Catch(interruptedexception e) + { A e.printstacktrace (); at } - } - - Public Static voidMain (string[] args) - { -Thread Thread1 =NewThread (NewMyThread2 ("One")); inThread thread2 =NewThread (NewMyThread2 ("the")); - Thread1.start (); to Thread2.start (); + } -}
The output is as shown above.
Java Learning (ix): Two ways to implement Java threads