多线程
实现多线程方式一: 继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
System.out.println(i);
}
}
}
//=============================================
public class Test1 {
public static void main(String[] args) {
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();
mt1.start();
mt2.start();
}
}
注意
1、为什么要重写run()方法
因为run()是用来封装杯线程执行的代码
2、run方法和start()方法的区别
run():封装线程执行的代码,直接调用,相当于普通方法调用
start():启动线程;由JVM调用此线程的run()方法
实现多线程方式二: 实现Runnable接口
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
}
//=================================
public class Test1 {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread t1 = new Thread(myRunnable);
Thread t2 = new Thread(myRunnable);
t1.start();
t2.start();
}
}
实现多线程方式二: 实现Callable接口
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
for (int i = 0; i <= 10; i++) {
System.out.println(i);
}
return "好的";
}
}
public class Test1 {
public static void main(String[] args) throws