Java多线程之实现多线程方法
1.Thread类
通过继承Thread类实现多线程
- 自定义线程类继承Thread类
- 重写Run()方法,编写线程执行体
- 创建线程对象,通过start()方法启动线程
public class TestThread1 extends Thread{
@Override
public void run() {
super.run();
for(int i =0;i<20;i++){
System.out.println("多线程---"+i);
}
}
public static void main(String[] args) {
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//开启线程
testThread1.start();
for(int i =0 ;i<20;i++){
System.out.println("主线程--"+i);
}
}
}
2.Runnable接口方法
- 定义MyRunnable类实现Runnabke接口
- 实现run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
//创建线程方法2:实现Runnable接口,或重写run方法,
public class TestThread3 implements Runnable{
@Override
public void run() {
for(int i=0;i<20;i++){
System.out.println("多线程--"+i);
}
}
public static void main(String[] args) {
new Thread(new TestThread3()).start();
for(int i =0;i<20;i++)
{
System.out.println("主线程--"+i);
}
}
}