线程运行的代码就是实现Runnable接口的类的run()方法或是Thread类的子类的run()方法
创建和运行线程的两种方法:
1.继承Thread 类并覆盖它的run()方法
2.实现Runnable接口实现run()方法
一、继承Thread 类
package threadTest;public class SimpleThread extends Thread {
public SimpleThread(String name){
super(name);
}
public void run(){
for(int i=0;i<100;i++){
System.out.println(getName()+"="+i);
try{
Thread.sleep((int)Math.random()*100);
}catch(InterruptedException e){}
}
System.out.println(getName()+"结束");
}
}
package threadTest;
public class OtherThread extends Thread {
public OtherThread(String name){
super(name);
}
public void run(){
System.out.println(2+"结束");
}
}
package threadTest;
public class ThreadTest {
public static void main(String [] args){
Thread a=new SimpleThread("线程a");
Thread b=new OtherThread("线程b");
a.start();
b.start();
}
}