创建线程
Java中创建线程又两种方式,一种是继承Thread类,一种是实现Runnable接口。对于Thread的继承类,直接new即可,对于Runnable的实现类,用这个接口的实现类来new一个线程。
代码示例如下:
//继承Thread类
public class FirstThread extends Thread {
//需要继承run方法
public void run() {
try {
for (int i = 0; i < 20; i++) {
sleep(500);
System.out.println(getName());
}
} catch (InterruptedException e) {
// 处理线程被终止的情况
e.printStackTrace();
}
}
}
//实现Runnable接口
public class SecondThread implements Runnable {
//Runnable接口只有一个run方法,必须实现。
public void run() {
try {
for (int i = 0; i < 20; i++) {
Thread.sleep(400);
System.out.println(Thread.currentThread().getName());
}
} catch (InterruptedException e) {
//处理线程被终止的情况
e.printStackTrace();
}
}
}
//执行线程
FirstThread t1 = new FirstThread();
t1.setName("thread1");
FirstThread t2 = new FirstThread();
t2.setName("thread2");
SecondThread r1 = new SecondThread();
Thread t3 = new Thread(r1);
Thread t4 = new Thread(r1);
t3.setName("thread3");
t4.setName("thread4");
t1.start();
t2.start();
t3.start();
t4.start();
需要注意,线程的执行必须使用start方法。