1 - 简单代码示例
- 继承Thread类
public class PrimeThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "-" + i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 测试类
public class testMain {
public static void main(String[] args) {
PrimeThread t1 = new PrimeThread();
PrimeThread t2 = new PrimeThread();
t1.start();
t2.start();
}
- 实现Runnable接口
public class PrimeRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "-" + i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 测试类
public class testMain {
public static void main(String[] args) {
Thread t1 = new Thread(new PrimeRunnable());
Thread t2 = new Thread(new PrimeRunnable());
t1.start();
t2.start();
}
-
上边两种方式, 输出结果类似 (看出 每次执行结果都不确定)
Thread-0-0 Thread-1-0 Thread-0-1 Thread-1-1 Thread-1-2 Thread-0-2 Thread-0-3 Thread-1-3 Thread-0-4 Thread-1-4 Thread-0-5 Thread-1-5 Thread-0-6 Thread-1-6 Thread-0-7 Thread-1-7 Thread-0-8 Thread-1-8 Thread-1-9 Thread-0-9
2 - 异常处理
- 出现了异常,线程中也不需向外抛,即使跑出来,主线程也不一定接收到