Java中的多线程
- 创建线程的方式:1.继承Thread类,重写run()方法,调用start开启线程
举个例子:
package thread;
public class TestThread01 extends Thread{
@Override
public void run() {
for(int i=1;i<20;i++){
System.out.println("haha"+i);
}
}
public static void main(String[] args) {
TestThread01 testThread01=new TestThread01();
testThread01.start();
for (int i=1;i<5;i++){
System.out.println("hehe"+i);
}
}
}
如上所示,在重写的run()方法中有for循环,而在main()方法中也有for循环,因为线程是交替执行的,所以结果应该是交替出现的
2.实现Runnable接口:定义MyRunnable类实现Runnable接口,实现run()方法,编写线程执行体,创建线程对象,调用start()方法启动线程
package thread;
public class TestThread02 implements Runnable {
@Override
public void run() {
for (int i = 1; i < 20; i++) {
System.out.println("haha" + i);
}
}
public static void main(String[] args) {
TestThread02 testThread02=new TestThread02();
Thread thread=new Thread(testThread02);
thread.start();
for (int i = 1; i < 5; i++) {
System.out.println("hehe" + i);
}
}
}
程序跟上边的差不多,唯一的区别是:在main()方法中,先创建了当前类的对象,又创建了Thread的对象,最终将当前类的对象注入到Thread对象内,并用Thread对象start线程