Java中,实现多线程有两种途径:继承java.lang.Thread类或者实现Runnable接口。
1.通过继承Thread实现多线程
package net.jerryblog.multithread;
public class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
for(int i = 0; i < 1000; i++) {
System.out.println("Thread " + i + "——>" + name);
}
}
public static void main(String[] args) {
MyThread th1 = new MyThread("Thread A");
MyThread th2 = new MyThread("Thread B");
th1.start();
th2.start();
}
}
需要说明的是,线程的启动,需要调用start()方法,不能直接调用run()方法。run()方法只是线程执行的一个模板,也就是说线程按照其中的代码执行。此外,循环中i的范围需要设置大一点,不然的话很可能看到的现象还是A线程执行完了所有次数才开始执行B线程。这是因为现在的电脑配置可能都比较好,设置的循环次数太小的话,可能在一个CPU时间片内,A线程就已经都执行完了。
对于继承Thread的类的一个实例,不能连续两次调用其start()方法。否则会抛出IllegalThreadStateException
package net.jerryblog.multithread;
public class TestIllegalThreadStateException extends Thread {
public void run() {
}
public static void main(String[] args) {
TestIllegalThreadStateException th = new TestIllegalThreadStateException();
th.start();
th.start();
}
}
这时就会报异常:
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:612)
at net.jerryblog.multithread.TestIllegalThreadStateException.main(TestIllegalThreadStateException.java:11)
2.实现Runnable接口
package net.jerryblog.multithread;
public class TestRunnable implements Runnable {
private String name;
public TestRunnable(String name) {
this.name = name;
}
public void run() {
for(int i = 0; i < 500; i++) {
System.out.println("Thread " + i + "——>" + name);
}
}
public static void main(String[] args) {
TestRunnable tr1 = new TestRunnable("Thread A");
TestRunnable tr2 = new TestRunnable("Thread B");
Thread t1 = new Thread(tr1);
Thread t2 = new Thread(tr2);
t1.start();
t2.start();
}
}