- 实现Runnable接口如果当前类 不仅要继承其他类( 非Thread类), 还要实现多线程,那么 只能通过当前类实现 Runnable接口来 创建Thread类对象。 实现Runnable接口的程序会创建一个Thread对象,并将Runnable接口的对象target作为其运行对象。Thread类的构造方法:构造方法 介绍 public Thread(Runnable target); 创建一个新的 Thread 对象。 public Thread(Runnable target , String name); 创建一个新的 Thread 对象,并指定名字。实现Runnable接口 实例:
import javax.swing.*;
import java.awt.*;
public class Demo1 extends JFrame implements Runnable {
private JLabel jLabel = new JLabel();
private int count = 0;
private Container c = getContentPane();
public Demo1(){
setBounds(400,200,250,100);
c.setLayout(null);
try{
Icon icon = new ImageIcon("src/setting.png");
jLabel.setIcon(icon);
}catch (NullPointerException e){
System.out.println("图片不存在");
return;
}
jLabel.setHorizontalAlignment(SwingConstants.LEFT);
jLabel.setBounds(10,10,200,50);
jLabel.setOpaque(true);
c.add(jLabel);
setVisible(true);
}
public static void main(String[] args) {
Demo1 demo1 = new Demo1();
Thread thread = new Thread(demo1);
thread.start();
}
@Override
public void run() {
int i = 10;
while (true){
jLabel.setBounds(i,10,200,50);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i+=5;
if (i>=200){
i=10;
}
}
}
}
Original: https://www.cnblogs.com/TeaTracing/p/16124143.html
Author: TeaTracing
Title: 实现线程的两种方式
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/622481/
转载文章受原作者版权保护。转载请注明原作者出处!