两个线程交叉运行
案例:编写一个程序,该程序可以接受一个整数n,创建两个线程,一个线程计算从1+...+n并输出结果,另一个线程每隔一秒在控制台输出一句话。这两个工作要同时进行。
代码:
public class TwoThread { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Pig pig = new Pig(); Bird brid = new Bird(10); Thread t1 = new Thread(pig); Thread t2 = new Thread(brid); t1.start(); t2.start(); } } class Pig implements Runnable { int n = 0; int times = 0; public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } times++; System.out.println("hello" + times); if (times == 10) { break; } } } } class Bird implements Runnable { int n = 0; int res = 0; int times = 0; public Bird(int n) { this.n = n; } public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } res += (++times); System.out.println("now is:" + res); if (times == n) { System.out.println("res is:" + res); break; } } } }执行结果:

本文介绍了一个使用Java实现的简单并发计算示例。通过创建两个线程,一个线程负责累加指定范围内的整数并输出结果,另一个线程则每隔一秒输出一行消息,展示了基本的线程交互。

被折叠的 条评论
为什么被折叠?



