各位高手,请问这个程序的了面的thread1和thread2的执行顺序是不是由cpu决定的?我发现它每一次的运行结果不一定一样,还有就是count的这个实例域可以在声明的时候初始化吗?实例域似乎只可以在构造器初始化的,让各位见笑,我刚学这个不久,有很多不懂public class SynchronizeArray implements Runnable
{
private int count = 1;
private int[] array = new int[6];
private Thread thread1;
private Thread thread2;
public SynchronizeArray()
{
thread1 = new Thread(this, "thread1");
thread1.start();
thread2 = new Thread(this, "thread2");
thread2.start();
} public synchronized void addnumber()
{
array[this.count] = count;
System.out.println(Thread.currentThread().getName() + ":" + array[count]);
count++;
} public void run()
{
for (int i = 0; i < 3; i++)
{
addnumber();
}
} public static void main(String[] args)
{ new SynchronizeArray();
}
}
{
private int count = 1;
private int[] array = new int[6];
private Thread thread1;
private Thread thread2;
public SynchronizeArray()
{
thread1 = new Thread(this, "thread1");
thread1.start();
thread2 = new Thread(this, "thread2");
thread2.start();
} public synchronized void addnumber()
{
array[this.count] = count;
System.out.println(Thread.currentThread().getName() + ":" + array[count]);
count++;
} public void run()
{
for (int i = 0; i < 3; i++)
{
addnumber();
}
} public static void main(String[] args)
{ new SynchronizeArray();
}
}
不过根据操作系统不同 线程的执行时间也不同