This blog: Introduction and use of JAVA threads
Thread creation
线程是程序中的执行流。
一个执行流是CPU运行程序代码并操作程序的数据所形成的。
因此,线程被认为是CPU为主体的行为。
线程的创建共有两个方法
Create thread by implementing Runnable interface
Implementation steps
(1) Define a class to implement the Runnable interface, that is, provide the implementation of the run() method in this class.
(2) Pass an instance of Runnable as a parameter to a constructor of the Thread class, and the instance object provides the thread body run().
Code example
public class ThreadTest {
public static void main(String[] args) {
Thread t1=new Thread(new Hello());
Thread t2=new Thread(new Hello());
t1.start();
t2.start();
}
}
class Hello implements Runnable{
int i;
public void run() {
while(true) {
System.out.println("Hello"+i++);
if(i==5) break;
}
}
}
operation result
(The result of each run of the same code may be different)
The following is a screenshot of the result of a run:
Create a thread by inheriting the Thread class
Implementation steps
(1) Derive a subclass from the Thread class and override the run() method to define the thread body.
(2) Create an object of this subclass to create a thread.
Code example
public class ThreadTest2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Hello1 t1=new Hello1();
Hello1 t2=new Hello1();
t1.start();
t2.start();
}
}
class Hello1 extends Thread{
int i;
public void run() {
while(true) {
System.out.println("Hello"+i++);
if(i==5)break;
}
}
}
operation result
(The results of the same code may be different on different computers)
The following is a screenshot of the results of a run:
Common basic control methods for threads
1.sleep()
sleep()方法能够把CPU让优先级比其低的线程。该方法使一个线程运行暂停一段固定的时间。在休眠时间内,线程将不运行。
sleep()方法的格式:
static void sleep(int millsecond)//休眠时间以毫秒为单位
static void sleep(int millsecond,int nanosecond)//休眠时间是指定的毫秒数与纳秒数之和
2.stop()
当线程完成运行并结束后,将不能再运行。线程除正常运行结束外,还可以用其他方法控制使其停止运行。用stop()方法,强制终止线程。但是该方法的调用容易造成线程的不统一,因此不提倡采用该方法
3.isAlive()
有时线程的状态可能未知,用isAlive()测试线程以确定线程是否活着。该方法返回值为true意味着线程已经启动但还没有运行结束。