用java编程实现两个定时线程,一个线程每隔1秒显示一次,另一个线程每隔3秒显示一次

来源:百度知道 编辑:UC知道 时间:2024/06/05 07:16:36
用java编程实现两个定时线程,一个线程每隔1秒显示一次,另一个线程每隔3秒显示一次,运行后效果如附件图片所示

public class Test {

Thread th1 = new Thread(new Th1());//定义线程1
Thread th2 = new Thread(new Th2());//定义线程2

public Test() {
this.th1.start();
this.th2.start();
}
public static void main(String[] args) {
new Test();
}
// 线程1
class Th1 implements Runnable {

public void run(){

while(true){
System.out.println("我是线程1");
try {
th1.sleep(1000);//一秒后再此运行
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
// 线程2
class Th2 implements Runnable {

public void run(){
while(true){
System.out.println("我是线程2");
try {