import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Jishiqi extends JFrame{
private JLabel fen;
private JLabel miao;
private static JButton buttonF;
private static JButton buttonM;
public JButton getFenzhong(){
return buttonF;
}
public JButton getMiaozhong(){
return buttonM;
}
public Jishiqi(){
super("线程计时器");
this.setBounds(200,200,300,200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new GridLayout(2,1));
JPanel time=new JPanel();
buttonF=new JButton("0");
buttonF.setEnabled(false);
fen=new JLabel("分");
time.add(buttonF);
time.add(fen);
buttonM=new JButton("0");
buttonM.setEnabled(false);
miao=new JLabel("秒");
time.add(buttonM);
time.add(miao);
this.add(time);
JPanel kaishi=new JPanel();
final JButton kai=new JButton("开始 ");
kai.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource()==kai){
Miao mi=new Miao();
mi.start();
Fen fe=new Fen();
fe.start();
}
}
});
kaishi.add(kai);
this.add(kaishi);
this.setVisible(true);
}
public static void main(String args[]){
new Jishiqi();
}
}
package 线程计时器;
public class Fen extends Thread{
public void run(){
Jishiqi ji=new Jishiqi();
synchronized(ji){
for(int i=0;i<=60;i++){
if(i==60){
i=0;
}
ji.getFenzhong().setText(""+i);
try{
Thread.sleep(60000);
}catch(InterruptedException e){
}
}
}
}
}
package 线程计时器;
public class Miao extends Thread{
public void run(){
Jishiqi ji=new Jishiqi();
synchronized(ji){
for(int i=0;i<=60;i++){
if(i==60){
i=0;
}
ji.getMiaozhong().setText(""+i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
}
}
}
}
}
还有为什么不用synchronized时,只能运行秒呢,这两个线程没用同一个对象啊,只是同一个类的不同对象,还有如果没有synchronized时直接用的类调用JButten时,那都能运行,这是为什么呢? |
-
3.JPG
(22.1 KB, 下载次数: 45)
|