package 线程优先级;
import java.awt.*;
import javax.swing.*;
public class MyThread extends JFrame {
static int i=0;
private static Thread thread[]=new Thread[4];
private static JProgressBar pb[]=new JProgressBar[4];
public MyThread(String title)
{
super(title);
Container container=this.getContentPane();
container.setLayout(new GridLayout(4,1));
for(int i=0;i<4;i++)
{
pb[i]=new JProgressBar();
pb[i].setStringPainted(true);
}
while(i<4)
{
thread[i]=new Thread(new Runnable(){
public void run(){
int progress=0;
while(progress<=100)
{
try{
Thread.sleep(100);
}catch(Exception e)
{
e.printStackTrace();
}
pb[i].setValue(progress++); //此处有问题
}
}
}
);
i++;
}
for(int i=0;i<4;i++)
container.add(pb[i]);
this.setSize(400,400);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
thread[0].setPriority(5);
thread[1].setPriority(5);
thread[2].setPriority(4);
thread[3].setPriority(3);
i=0;
while(i<4)
{
thread[i].start();
i++;
}
}
public static void main(String[] args)
{
new MyThread("线程优先级");
}
}
这段代码由于我在run()方法里设置进度条的数字时用了静态变量,导致在调用线程start()方法的时候里面的进度条只动了一条。如果不用静态变量的话我又不知道怎么在Runnable的匿名内部类中访问外部循环的i,有没有什么办法在匿名内部类中能够访问外部的参数,而且不是常量不是静态变量?