java多线程交互
用简单小案例实现一下java多线程交互
package com.test5;
public class LWP_InteractionTest {
public static void main(String[] args){
Pig p = new Pig(10);
Bird b = new Bird(10);
Thread t1 = new Thread(p);
Thread t2 = new Thread(b);
t1.start();
t2.start();
}
}
class Pig implements Runnable{
int times = 0;
int n=0;
public Pig(int n){
this.n = n;
}
public void run(){
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("我是一个线程,在输出第"+times+"个HelloWorld!");
times++;
if(times==n)
break;
}
}
}
class Bird implements Runnable{
int ans = 0;
int times = 0;
int n = 0;
public Bird(int n){
this.n = n;
}
public void run(){
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ans += (times++);
System.out.println("当前结果是"+ans);
if(times==n)
break;
}
System.out.println("最后结果是:"+ans);
}
}
运行结果为: