两个线程交叉运行
案例:编写一个程序,该程序可以接受一个整数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;
}
}
}
}
执行结果: