JAVA中有两种实现线程的方法
1.继承Thread
public class JavaThread {
public static void main(String[] args) {
Hello h1=new Hello("A");
Hello h2=new Hello("B");
h1.start();
h2.start();
}
}
class Hello extends Thread{
private String name;
public Hello(String name){
this.name=name;
}
public void run(){
for(int i=0;i<5;i++){
System.out.println(name+"运行 "+i);
}
}
}
2.实现Runnable
public class JavaThreadRunnable {
public static void main(String[] args) {
Hellos h1=new Hellos("A");
Hellos h2=new Hellos("B");
Thread th1=new Thread(h1);
Thread th2=new Thread(h2);
th1.start();
th2.start();
}
}
class Hellos implements Runnable{
private String name;
public Hellos(String name){
this.name=name;
}
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println(name + "运行 " + i);
}
}
}