JAVA 几种多线程的简单实例 Thread Runnable

实例1:
class Hello extends Thread{
private String name;
public Hello(){}
public Hello(String name){
this.name = name;
}
public void run(){
for(int i=0;i<100;i++){
System.out.println(this.name + i);
}
}
public static void main(String[] args){
Hello h1 = new Hello("A");
Hello h2 = new Hello("B");
h1.run();
h2.run();
}
}
这样的办法输出的结果会是顺序运行,不符合我们想要的多线程运行效果,接下来看 实例2:
class Hello extends Thread{
private String name;
public Hello(){}
public Hello(String name){
this.name = name;
}
public void run(){
for(int i=0;i<100;i++){
System.out.println(this.name + i);
}
}
public static void main(String[] args){
Hello h1 = new Hello("A");
Hello h2 = new Hello("B");
h1.start();
h2.start();
}
}
实例3:
class Hello implements Runnable{
private String name;
public Hello(){}
public Hello(String name){
this.name = name;
}
public void run(){
for(int i=0;i<100;i++){
System.out.println(this.name + i);
}
}
public static void main(String[] args){
Hello h1 = new Hello("A");
Thread t1 = new Thread(h1);
Hello h2 = new Hello("B");
Thread t2 = new Thread(h2);
t1.start();
t2.start();
}
}
原文地址:https://www.cnblogs.com/liguangsunls/p/7207746.html