线程的两种实现方式
- 1、继承thread类
- 2、实现Runnable接口,推荐使用
package com.wuzl;
/**
*线程的两种实现方式
* 1、继承thread类
* 2、实现Runnable接口,推荐使用
*/
public class test01 {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();//启动线程
//推荐使用
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr);
t.start();//启动线程
//mt与t线程可能交叉执行
}
}
/**
* 继承线程的第一种方式
* 继承thread类
*/
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "-->" + i);
}
}
}
/**
* 实现线程的第二种方式
* 实现Runnable接口
* 推荐使用
*/
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println(Thread.currentThread().getName() + "-->" + i);
}
}
}