同时开启多个线程,基本思想(重写每个线程中的run函数)
e.g.
主函数:
package _pasted_code_;
public class Testwork {
public static void main(String args[]){
new T1().start();
new T2().start();
}
}
T1:
package _pasted_code_;
import java.util.Date;
public class T1 extends Thread{
public void run(){
Date date=new Date();
String s=String.format("%tS", date);
while(true){
try {
System.out.println(s+"from 1");
Thread.sleep(1000);
date=new Date();
s=String.format("%tS", date);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
T2:
package _pasted_code_;
import java.util.Date;
public class T2 extends Thread{
Date date=new Date();
String s=String.format("%tS", date);
public void run(){
while(true){
try {
System.out.println(s+"from 2");
Thread.sleep(2000);
date=new Date();
s=String.format("%tS", date);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
运行结果:
48from 1
48from 2
49from 1
50from 2
50from 1
51from 1
52from 2
52from 1
53from 1
54from 1
54from 2
55from 1