问一个关于线程的问题,一直不是弄的很清楚!
package com.pos.test;
public class SimpleThread extends Thread {
public int countDown = 5;
private static int threadCount = 0;
private int threadNumber = ++threadCount;
public SimpleThread(){
System.out.println( "making "+threadNumber);
}
public void run(){
while(true){
System.out.println( "thread "+threadNumber+ "( "+countDown+ ") ");
if(--countDown==0) return;
}
}
/**
* @param args
*/
public static void main(String[] args) {
for(int i =0;i <5;i++)
new SimpleThread().start();
System.out.println( "end ");
}
}
这是thinkinjava的原程序,运行是正常的,下面是我改的程序,问什么就发生了并发的问题,刚开始学习线程,对同一个类实例化的线程对象是否共享一块内存,是否每个对象中的变量相互独立弄的不是很清楚,希望有知道的能给我一点帮助!
public class SimpleThread implements Runnable {
public int countDown = 5;
private static int threadCount = 0;
private int threadNumber = ++threadCount;
public SimpleThread(){
System.out.println( "making "+threadNumber);
}
public void run(){
while(true){
System.out.println( "thread "+threadNumber+ "( "+countDown+ ") ");
if(--countDown==0) return;
}
}
/**
* @param args
*/
public static void main(String[] args) {
SimpleThread st = new SimpleThread();
for(int i =0;i <5;i++)
new Thread(st).start();
System.out.println( "end ");
}
}
------解决方案--------------------把你第二个程序改了一下:
package com.whj.jdk.lang;
public class SimpleThread extends Thread {
private static int threadCount = 0;
/**
* @param args
*/
public static void main(String[] args) {
SimpleThread st = new SimpleThread(); // Error Code
for (int i = 0; i < 5; i++) {
// new SimpleThread().start();
new Thread(st).start(); // Error Code
}
System.out.println( "end ");
}
public int countDown = 5;
private final int threadNumber = ++threadCount;
public SimpleThread() {
System.out.println( "making " + threadNumber);
}
@Override
public void run() {
while (true) {
System.out.println( "thread " + threadNumber + "( " + countDown + ") ");
if (--countDown == 0) {
System.out.println( "GO ");
return;
}
}
}
}
运行后的输出结果是:
making 1
end
thread1(5)
thread1(4)
thread1(3)
thread1(2)
thread1(1)
GO
thread1(0)
thread1(-1)
thread1(-2)
thread1(-3)
thread1(-4)
thread1(-5)
thread1(-6)
thread1(-7)
thread1(-8)
thread1(-9)
thread1(-10)
thread1(-11)
thread1(-12)
thread1(-13)
thread1(-14)
以下被我中断。
你仔细分析一下就知道为什么了。
------解决方案--------------------