JAVA 几种多线程的简单实例 Thread Runnable
生活随笔
收集整理的這篇文章主要介紹了
JAVA 几种多线程的简单实例 Thread Runnable
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
實例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();
}
}
這種辦法輸出的結果會是順序執(zhí)行,不符合我們想要的多線程執(zhí)行效果,接下來看 實例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();
}
}
總結
以上是生活随笔為你收集整理的JAVA 几种多线程的简单实例 Thread Runnable的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Git管理软件
- 下一篇: highcharts 绘制图标的JAVA