Java学习 Day01 多线程
Java多线程实现方式有 2 种
1.继承 Thread 类,重写 run 方法
- 案例
- 测试类 Thread01
package top.wanqq.thread;
/**
- @author wanqq
- /
public class Thread01 extends Thread {
@Override
public void run() {
} }for (int i = 0; i < 200; i++) { System.out.println("-------" + i); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } }
- 主类 ThreadIndex
```Java
package top.wanqq.thread;
/**
* @author wanqq
*/
public class ThreadIndex {
public static void main(String[] args) {
new Thread01().start();
for (int i = 0; i < 200; i++) {
System.out.println("Thread index :" + i);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 结果
2.实现 Runnable 接口
- 测试类 RunnableThreadTest
package top.wanqq.thread;
/**
@author wanqq
/ public class RunnableThreadTest implements Runnable{
@Override public void run() {
for (int i = 0; i < 10; i++) { System.out.println("runnable test :" + i); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } }
} }
- 主类 ThreadIndex
```java
package top.wanqq.thread;
/**
* @author wanqq
*/
public class ThreadIndex {
public static void main(String[] args) {
new Thread(new RunnableThreadTest()).start();
for (int i = 0; i < 10; i++) {
System.out.println("Thread index :" + i);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 结果