如果要让其他类使用线程就要用到runnable,其他thread就是实现了runnbale接口,其中run()方法就是对runnable接口中的run()方法的具体实现。有两个构造函数分别是:public thread(runnable)、public thread(runnable r,string name) 使用runnable接口实现了启动新的线程步骤如下: 1、创建runnable对象。2、使用参数为runnable对象的构造方法创建thread实例。3、调用start()方法启动线程。 下面结合swing来练习一下:
1 package hengzhe.cn.o1;
2
3 import java.awt.Container;
4 import java.net.URL;
5
6 import javax.swing.Icon;
7 import javax.swing.ImageIcon;
8 import javax.swing.JFrame;
9 import javax.swing.JLabel;
10 import javax.swing.SwingConstants;
11 import javax.swing.WindowConstants;
12
13 public class SwingAndThread extends JFrame
14 {
15 private JLabel jl = new JLabel();
16 private static Thread t;//线程对象
17 private int count = 0;
18 private Container container = getContentPane();//容器
19
20 public SwingAndThread()
21 {
22 setBounds(300, 200, 250, 100);//窗体大小与位置
23 container.setLayout(null);
24
25 Icon icon = new ImageIcon("E:\\ymnl.png");
26 jl.setIcon(icon);
27 jl.setHorizontalAlignment(SwingConstants.LEFT);//图片的位置
28 jl.setBounds(10, 10, 200, 50);//标签的大小
29 jl.setOpaque(true);
30 t = new Thread(new Runnable() //匿名类,实现runnable接口
31 {
32 public void run()//重写run()方法
33 {
34 while (count <= 200)//设置循环条件
35 {
36 jl.setBounds(count, 10, 200, 50);
37 try
38 {
39 t.sleep(1000);//休眠1000毫秒
40 } catch (Exception ex)
41 {
42 ex.printStackTrace();
43 }
44 count += 4;//图片的位置增加四
45 if (count == 200)
46 {
47 count = 10;//当图片到最右边时,让图片再到左边
48 }
49 }
50
51 }
52
53 });
54 t.start();//启动
55 container.add(jl);//添加容器中
56 setVisible(true);//可见
57 setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
58 }
59
60 public static void main(String[] args)
61 {
62 new SwingAndThread();//调用主体
63
64 }
65
66 }
View Code
转载于:https://www.cnblogs.com/c546170667/p/5910899.html