实现Runable
public class MyRunable implements Runnable {
String str;
public MyRunable(String str) {
this.str = str;
}
@Override
public void run() {
for(int i = 1; i <= 10; i++) {
System.out.println(str+" "+i);
}
}
}
继承Thread
public class MyThread extends Thread{
String str;
public MyThread(String str) {
this.str = str;
}
@Override
public void run() {
for(int i = 1; i <= 10; i++) {
System.out.println(str+" "+i);
}
}
}
测试代码
import org.junit.jupiter.api.Test;
public class ThreadTest {
/**
* 继承Thread实现多线程
*/
@Test
public void testThread(){
MyThread myThread1=new MyThread("myThread1");
MyThread myThread2=new MyThread("myThread2");
myThread1.start();
myThread2.start();
}
/**
* 实现Runable接口实现多线程
*/
@Test
public void testRunable(){
MyRunable myRunable1=new MyRunable("myRunable1");
MyRunable myRunable2=new MyRunable("myRunable2");
Thread thread1=new Thread(myRunable1);
Thread thread2=new Thread(myRunable2);
thread1.start();
thread2.start();
}
}