java中 synchronized同步处理后 为什么只有一个线程在运行
packagecom.java.zuoye;importjava.util.Random;classThreadSalesimplementsRunnable{publi...
package com.java.zuoye;
import java.util.Random;
class ThreadSales implements Runnable {
public synchronized void get() {
int num = 0;
for (int i = 1; i <= 1000; i++) {
if (num < 2000) {
Random random = new Random();
int price = random.nextInt(101);
num = price + num;
System.out.println(Thread.currentThread() + "赚了" + price + ",总共" + num);
} else {
System.out.println("赚钱结束");
System.exit(0);
}
try {
Thread.sleep((int) (1000 * Math.random()));
} catch (Exception e) {
}
}
}
public void run() {
while (true) {
get();
}
}
}
public class zuoye11_01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadSales num = new ThreadSales();
Thread t1 = new Thread(num, "小明");
Thread t2 = new Thread(num, "小花");
Thread t3 = new Thread(num, "小军");
t1.start();
t2.start();
t3.start();
}
} 展开
import java.util.Random;
class ThreadSales implements Runnable {
public synchronized void get() {
int num = 0;
for (int i = 1; i <= 1000; i++) {
if (num < 2000) {
Random random = new Random();
int price = random.nextInt(101);
num = price + num;
System.out.println(Thread.currentThread() + "赚了" + price + ",总共" + num);
} else {
System.out.println("赚钱结束");
System.exit(0);
}
try {
Thread.sleep((int) (1000 * Math.random()));
} catch (Exception e) {
}
}
}
public void run() {
while (true) {
get();
}
}
}
public class zuoye11_01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadSales num = new ThreadSales();
Thread t1 = new Thread(num, "小明");
Thread t2 = new Thread(num, "小花");
Thread t3 = new Thread(num, "小军");
t1.start();
t2.start();
t3.start();
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询