在Java语言中实现线程的第一种方式:
/**
*
* 在Java中实现线程的第一种方式:
* 继承java.lang.Thread
* 重写run方法
*
* 启动线程:
*
* 创建线程 new --> 启动线程 start方法
*
*/
public class ThreadTest01 {
public static void main(String[] args) {
//创建线程
Thread thread = new Processor();
//启动线程
thread.start();
//注意:thread.run()只是调用Processor类中的run方法,并不开启新线程,也不会创建栈内存
for (int i = 0; i < 30; i++) {
System.out.println("main----->"+i);
}
}
}
//定义一个线程类
class Processor extends Thread{
//重写run方法
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("run--->" + i);
}
}
}
在Java语言中实现线程的第二种方式:(推荐使用这种方式)
/**
* java中实现线程的第二种方式:
* 继承java.lang.Runnable;接口
* 实现run方法
* @author ztj
*
*/
public class ThreadTest02 {
public static void main(String[] args) {
//创建线程
Thread thread = new Thread(new Processor02());
//启动线程
thread.start();
}
}
//推荐使用这种方式,因为这个类实现接口之外还保留了类的继承
class Processor02 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("run---->"+ i);
}
}
}