- public class mainTestImpl {
- /*
- * 任何线程一般具有五种状态,即创建、就绪、运行、阻塞、终止 线程 调用stop()方法时或run()方法执行
- * 结束后,线程即处于死亡状态。 处于死亡状态的线程不具有继续运行的能力。
- */
- public static void main(String[] args) {
- testThread t = new testThread();
- t.run(); // start是启动一个线程由程序来调用run方法
- // run 是运行一个方法,等结束以后再执行后面的代码,不能达到多线程目的
- System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
- }
- }
- // 通过类继承必须有run方法,因为start启动线程后由程序调用run方法
- // Thread同样实现了Runnable接口
- class testThread extends Thread {
- public void run() {
- for (int i = 0; i < 5; i++) {
- try {
- Thread.currentThread().sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("runnable=" + Thread.currentThread().getName() + " " + i);
- }
- //new threadImp().run();
- }
- }
public class mainTestImpl {
/*
* 任何线程一般具有五种状态,即创建、就绪、运行、阻塞、终止 线程 调用stop()方法时或run()方法执行
* 结束后,线程即处于死亡状态。 处于死亡状态的线程不具有继续运行的能力。
*/
public static void main(String[] args) {
testThread t = new testThread();
t.run(); // start是启动一个线程由程序来调用run方法
// run 是运行一个方法,等结束以后再执行后面的代码,不能达到多线程目的
System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
}
}
// 通过类继承必须有run方法,因为start启动线程后由程序调用run方法
// Thread同样实现了Runnable接口
class testThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable=" + Thread.currentThread().getName() + " " + i);
}
//new threadImp().run();
}
}
运行后的结果如下:
runnable=main 0
runnable=main 1
runnable=main 2
runnable=main 3
runnable=main 4
main 线程运行结束!
可以看到都是main线程在运行,并不是期望的多线程。原因就在于调用了run()方法,将如上对应代码段改为如下后运行:
t.start(); // start是启动一个线程由程序来调用run方法
// run 是运行一个方法,等结束以后再执行后面的代码,不能达到多线程目的
- main 线程运行结束!
- runnable=Thread-0 0
- runnable=Thread-0 1
- runnable=Thread-0 2
- runnable=Thread-0 3
- runnable=Thread-0 4
main 线程运行结束!
runnable=Thread-0 0
runnable=Thread-0 1
runnable=Thread-0 2
runnable=Thread-0 3
runnable=Thread-0 4
修改testThread线程类并且增加一个实现Runnable接口的线程类,代码如下:
- // 通过类继承必须有run方法,因为start启动线程后由程序调用run方法
- // Thread同样实现了Runnable接口
- class testThread extends Thread {
- public void run() {
- new threadImp().run(); // 启动线程
- }
- }
- class threadImp implements Runnable {
- // 线程的几个状态,判断属性,计数次数,同步方法
- public void run() {
- for (int i = 0; i < 50; i++) {
- System.out.println("runnable=" + Thread.currentThread().getName() + " " + i);
- }
- }
- }
// 通过类继承必须有run方法,因为start启动线程后由程序调用run方法
// Thread同样实现了Runnable接口
class testThread extends Thread {
public void run() {
new threadImp().run(); // 启动线程
}
}
class threadImp implements Runnable {
// 线程的几个状态,判断属性,计数次数,同步方法
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println("runnable=" + Thread.currentThread().getName() + " " + i);
}
}
}
通过mainTestImpl类中的testThread类的run方法来启动另外一个线程,
发现运行的结果还是单线程,不知道为什么。。。。。。。