1. 使用 extends继承Thread类,然后在 主函数中 调用创建的这个类,创建其类对象,然后再利用对象访问start 方法。
package testThread;
public class thr {
public static void main(String args[]) throws InterruptedException{
for(int j =0;j<200;j++){
System.out.println(Thread.currentThread().getName()+" "+j);
if(j==50){
Thread.sleep(3000);
Thread th1 = new MyThread();
Thread th2 = new MyThread();
th1.start();
th2.start();
}
}
}
}
class MyThread extends Thread{
public void run()
{
for(int i = 0;i<100;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
2. 实现Runnable这个接口,再在主类里面调用这个接口,调用的方式是通过传参的方式,看代码就明白了。
package testThread;
public class thr1 {
public static void main(String args[]){
for(int j = 0;j<150;j++){
System.out.println(Thread.currentThread().getName()+" "+j);
if(j==60){
try{
Thread.sleep(5000);
}catch(Exception e){
e.printStackTrace();
}
Thread th1 = new Thread(new runn());
Thread th2 = new Thread(new runn());
th1.start();
th2.start();
}
}
}
}
class runn implements Runnable{
public void run(){
for(int i = 0;i<100;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
希望能够帮到你~~~