一、进程运行流程
1.每个程序至少自动拥有一个线程,称为主线程。
2.当程序加载到内存时启动主线程
3.Java程序中的public static void main()方法是主线程的入口,运行Java程序时,会先执行这个方法。
二、自定义线程的两种方式
1.实现Runable接口(推荐)
由于Java 是单根继承,而接口实现却可以多个,所以当一个类实现了Runabe接口,还能实现或继承其他,这样的类扩展性大大提高。
MyThread类:
public class MyThread implements Runnable{
// 重写接口中的run()方法
@Override
public void run() {
// Thread类中有静态方法currentThread(),此方法返回当前线程
Thread thread = Thread.currentThread();
// getName()方法 返回当前线程的名称
for (int i = 1; i <= 20; i++) {
System.out.println(i + "." + thread.getName());
}
}
}
测试类:
public class Test {
public static void main(String[] args) {
//创建进程
//MyThread类实现接口没有start()方法,需要创建Thread类对象
MyThread myThread = new MyThread();
// 将myThread对象当参数给构造方法
Thread thread = new Thread(myThread,"你好,来自线程Thread-1");
Thread thread1 = new Thread(myThread,"你好,来自线程Thread-2");
// 调用Start()方法 会自动调用run()方法
// 如果直接调用run()方法 启动的是主线程
thread.start();
thread1.start();
}
}
运行效果:
2.继承Thread类
继承Thread类后,在使用上比第一种方便,但由于Java的单根继承,该类后续不能再继承其他类,拓展性下降。
MyThread类:
public class MyThread extends Thread {
//使用继承方式创建进程
//重写run()方法
@Override
public void run() {
// 获取当前线程
Thread thread = Thread.currentThread();
for (int i = 1; i <= 20; i++) {
System.out.println(i + ".你好,来自线程" + thread.getName());
}
}
}
测试类:
public class Test {
public static void main(String[] args) {
//创建进程
MyThread myThread = new MyThread();
MyThread myThread1 = new MyThread();
//设置名称
myThread.setName("Hello");
//调用start()方法
myThread.start();
myThread1.start();
}
}
运行效果: