import java.util.concurrent.TimeUnit;
public class SynchronizedTest1 extends Thread {
public static int n = 0;
public void run() {
try {
//使n自加10次
for (int i = 0; i < 10; i++) {
n = n + 1;
TimeUnit.MILLISECONDS.sleep(10);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[100];
for (int i = 0; i < threads.length; i++) {
threads[i] = new SynchronizedTest1();
threads[i].start();
}
//使所有其他线程执行完,再继续执行main线程,这样得出的n是最终的结果
for (Thread thread : threads) {
thread.join();
}
System.out.println(n);
}
}
import java.util.concurrent.TimeUnit;
public class SynchronizedTest2 extends Thread {
public static int n = 0;
public synchronized void increase() {
n++;
}
public void run() {
try {
//使n自加10次
for (int i = 0; i < 10; i++) {
increase();
TimeUnit.MILLISECONDS.sleep(10);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[100];
for (int i = 0; i < threads.length; i++) {
threads[i] = new SynchronizedTest2();
threads[i].start();
}
//使所有其他线程执行完,再继续执行main线程,这样得出的n是最终的结果
for (Thread thread : threads) {
thread.join();
}
System.out.println(n);
}
}
import java.util.concurrent.TimeUnit;
public class SynchronizedTest3 extends Thread {
public static int n = 0;
public synchronized static void increase() {
n++;
}
public void run() {
try {
//使n自加10次
for (int i = 0; i < 10; i++) {
increase();
TimeUnit.MILLISECONDS.sleep(10);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[100];
for (int i = 0; i < threads.length; i++) {
threads[i] = new SynchronizedTest3();
threads[i].start();
}
//使所有其他线程执行完,再继续执行main线程,这样得出的n是最终的结果
for (Thread thread : threads) {
thread.join();
}
System.out.println(n);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有