天天看點

Thread多線程(二):Runnable

    如果要讓其他類使用線程就要用到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

Thread多線程(二):Runnable
Thread多線程(二):Runnable

轉載于:https://www.cnblogs.com/c546170667/p/5910899.html