基础Java题 试编写一个多线程的程序:启动4个线程。其中两个循环10次,每次将某全局变量加1,另两个循环1
试编写一个多线程的程序:启动4个线程。其中两个循环10次,每次将某全局变量加1,另两个循环10次,每次将此变量减1。请输出该变量的变化结果。...
试编写一个多线程的程序:启动4个线程。其中两个循环10次,每次将某全局变量加1,另两个循环10次,每次将此变量减1。请输出该变量的变化结果。
展开
1个回答
展开全部
public class Day18_A {
public static void main(String[] args) throws InterruptedException {
Recoun rec = Recoun.getRec();
Thread[] trr = new Thread[4];
for (int i = 0; i < 4; i++) {
trr[i] = new Thread(new NumberTest(rec, i), "线程" + (i + 1) + ":\t");
}
for (Thread thread : trr) {
thread.start();
}
for (Thread thread : trr) {
thread.join();
}
System.out.println("所有线程结束查看结果:" + rec.getCount());
}
}
class NumberTest implements Runnable {
private Recoun re;
private int n;
NumberTest(Recoun r, int i) {
this.re = r;
this.n = i;
}
public void run() {
for (int i = 0; i < 10; i++) {
re.method(n);
}
}
}
class Recoun {
private int count = 0;
private Recoun() {
}
private static final Recoun rec = new Recoun();
public static Recoun getRec() {
return rec;
}
public synchronized void method(int i) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + (count++));
} else {
System.out.println(Thread.currentThread().getName() + (count--));
}
}
public synchronized int getCount() {
return count;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询