3、 用实现接口Runable方式写一个三线程的程序,分别求出0的和,0+1的和,0+1+2的和,以及0+1+2+…+100的和,给线程加同步方法
时间: 2023-12-23 19:06:05 浏览: 65
线程类实现Runnable接口
这是一个经典的多线程问题,可以用实现接口Runable的方式来实现。
下面是一个示例代码,实现了三个线程分别计算0-99,0-100和0-101的和,最后将结果打印出来。
```java
public class ThreeThreadSum implements Runnable {
private int start;
private int end;
private int sum;
public ThreeThreadSum(int start, int end) {
this.start = start;
this.end = end;
this.sum = 0;
}
public synchronized void add(int num) {
sum += num;
}
public int getSum() {
return sum;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
add(i);
}
}
public static void main(String[] args) throws InterruptedException {
ThreeThreadSum t1 = new ThreeThreadSum(0, 99);
ThreeThreadSum t2 = new ThreeThreadSum(0, 100);
ThreeThreadSum t3 = new ThreeThreadSum(0, 101);
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t2);
Thread thread3 = new Thread(t3);
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
int sum1 = t1.getSum();
int sum2 = t2.getSum();
int sum3 = t3.getSum();
System.out.println("0-99的和:" + sum1);
System.out.println("0-100的和:" + sum2);
System.out.println("0-101的和:" + sum3);
System.out.println("0-100的和:" + (sum1 + sum2 + sum3));
}
}
```
在每个线程中使用同步方法add()来计算和,保证了线程安全。最后通过join()方法等待所有线程的执行完成,再将结果加起来输出。
阅读全文