java编写程序,用两个线程共同完成,每隔一秒向屏幕按顺序输出1-10的整数。
1个回答
展开全部
你好,好高兴为你解如散答,希望可以帮到你!以下代码实现了你要求的功能,运行结果如下所示:
**************************************************运行结果*******************************************************
1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 1 1 2 2
**************************************************运渣轿氏行帆扒结果*******************************************************
**************************************************程序源码*******************************************************
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author yekeliang
*/
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(new CountNumThread());
t1.start();
Thread t2 = new Thread(new CountNumThread());
t2.start();
}
}
class CountNumThread implements Runnable {
private boolean notFinished = true;
@Override
public void run() {
while (notFinished) {
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
**************************************************运行结果*******************************************************
1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 1 1 2 2
**************************************************运渣轿氏行帆扒结果*******************************************************
**************************************************程序源码*******************************************************
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author yekeliang
*/
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(new CountNumThread());
t1.start();
Thread t2 = new Thread(new CountNumThread());
t2.start();
}
}
class CountNumThread implements Runnable {
private boolean notFinished = true;
@Override
public void run() {
while (notFinished) {
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询