java基础之多线程二:多线程实现方式

时间:2024-04-09 14:34:51
方式一: 继承Thread类.
/*
* main函数也叫主函数(也叫主线程),
* 因为所有代码的执行都是从这里开始的.
*/
public static void main(String[] args) {
// 在测试类中,创建线程对象.
MyThread mt1 = new MyThread(); // 开启线程. //start()
//mt1.run(); //如果调用run()方法, 只是普通的方法调用.
mt1.start(); //开启线程必须调用start()方法, 该方法会自动去调用run()方法.
//mt1.start(); //同一线程不能重复开启, 否则会报: IllegalThreadStateException异常. for (int i = 1; i <= 100; i++) {
System.out.println("main...." + i);
}
} /**
* 自定义的线程类: MyThread
* @author
*
*/
// 1) 定义一个类(MyThread), 继承Thread类.
public class MyThread extends Thread{
//2) 重写Thread#run(). @Override
public void run() {
//3) 把要执行的代码放入run()方法中.
for (int i = 1; i <= 100; i++) {
System.out.println("run______________" + i);
}
}
}
方式二: 实现Runnable接口.
public static void main(String[] args) {
//格式化代码: alt + shift + s --> 字母f // 在测试类中, 创建Runnable接口的子类对象,
MyRunnable mr = new MyRunnable();
// 并将其作为参数传入Thread类的构造, 创建线程对象.
Thread th = new Thread(mr); // 开启线程. //start()
th.start(); for (int i = 1; i <= 100; i++) {
System.out.println("main***" + i);
} } /**
* Runnable接口的具体实现类
* @author
*
*/
//1) 定义一个类(MyRunnable), 实现Runnable接口.
public class MyRunnable implements Runnable {
//2) 重写Runnable#run().
@Override
public void run() {
//3) 把要执行的代码放入run()方法中.
for (int i = 1; i <= 100; i++) {
System.out.println("run______________" + i);
}
}
}

相关文章