package com.jckb;
/**多线程实现的两种方法
*
* @author gx
*
*/
public class Test2 {
public static void main(String[] args) {
Mythread m = new Mythread();
m.start();// 不能直接调用run方法
// m.run();//是方法调用,不是线程的启动
Thread t = new Thread(new Mythread2());
t.start();
}
}
// 线程停止的方法是run方法返回
// flag=false退出
// 线程停止后不能再次启动
class Mythread extends Thread {
@Override
public void run() {
boolean flag = true;
int i = 1;
while (flag) {
System.out.println("i=" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
if (i == 5) {
flag = false;
// return;
}
}
}
}
class Mythread2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("i=" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
![](https://images2015.cnblogs.com/blog/984360/201701/984360-20170101182717070-634879993.jpg)