public class JoinThread extends Thread {
public static volatile int n = 0; public void run() {
for (int i = 0; i < 10; i++, n++)
try {
sleep(3); // 为了使运行结果更随机,延迟3毫秒
} catch (Exception e) {
}
} public static void main(String[] args) throws Exception {
Thread threads[] = new Thread[100];
for (int i = 0; i < threads.length; i++)
// 建立100个线程
threads[i] = new JoinThread();
for (int i = 0; i < threads.length; i++)
// 运行刚才建立的100个线程
threads[i].start();
for (int i = 0; i < threads.length; i++)
// 100个线程都执行完后继续
threads[i].join();
System.out.println("n=" + JoinThread.n);
}
}输出结果达不到预期的1000
public static volatile int n = 0; public void run() {
for (int i = 0; i < 10; i++, n++)
try {
sleep(3); // 为了使运行结果更随机,延迟3毫秒
} catch (Exception e) {
}
} public static void main(String[] args) throws Exception {
Thread threads[] = new Thread[100];
for (int i = 0; i < threads.length; i++)
// 建立100个线程
threads[i] = new JoinThread();
for (int i = 0; i < threads.length; i++)
// 运行刚才建立的100个线程
threads[i].start();
for (int i = 0; i < threads.length; i++)
// 100个线程都执行完后继续
threads[i].join();
System.out.println("n=" + JoinThread.n);
}
}输出结果达不到预期的1000
虽然增量操作(x++)看上去类似一个单独操作,实际上它是一个由读取-修改-写入操作序列组成的组合操作,必须以原子方式执行,而 volatile 不能提供必须的原子特性。实现正确的操作需要使 x 的值在这种组合操作期间保持不变,而 volatile 变量无法实现这点。因此,你的程序无法正确使用volatile
这个不行,volatile 修饰的不能随便用,n++非原子操作
程序改成这个样子就没有问题了: private static int n = 0; public static synchronized void count() {
n++;
} public void run() {
for (int i = 0; i < 10; i++) {
count();
try {
sleep(3); // 为了使运行结果更随机,延迟3毫秒
} catch (Exception e) {
}
}
}
class Outmethod {
public synchronized void method(int n) {
n++;
}
}
public class JoinThread extends Thread {
public static int n = 0;
private Outmethod om;
public JoinThread(Outmethod om){
this.om = om;
} public void run() {
for (int i = 0; i < 10; i++)
om.method(n);
try {
sleep(3); // 为了使运行结果更随机,延迟3毫秒
} catch (Exception e) {
}
} public static void main(String[] args) throws Exception {
Outmethod om = new Outmethod();
Thread threads[] = new Thread[100];
for (int i = 0; i < threads.length; i++)
// 建立100个线程
threads[i] = new JoinThread(om);
for (int i = 0; i < threads.length; i++)
// 运行刚才建立的100个线程
threads[i].start();
for (int i = 0; i < threads.length; i++)
// 100个线程都执行完后继续
threads[i].join();
System.out.println("n=" + JoinThread.n);
}
}
public synchronized void method(int n) {
n++;
}
方法并不改变传入的参数本身,所以必然是0
return n++;
}
试一试
这是我的程序,对你的程序稍作修改,请楼主看看:public class JoinThread extends Thread {
public static volatile int n = 0; public void run() {
for (int i = 0; i < 10; i++, n++)
try {
sleep(3); // 为了使运行结果更随机,延迟3毫秒
} catch (Exception e) {
}
} public static void main(String[] args) throws Exception {
Thread threads[] = new Thread[100];
for (int i = 0; i < threads.length; i++){
// 建立100个线程
threads[i] = new JoinThread();
// 运行刚才建立的100个线程
threads[i].start();
threads[i].join();
}
System.out.println("n=" + JoinThread.n);
}
}