java之线程

1.线程是程序中一个单一的顺序控制流程。进程内一个相对独立的、可调度的执行单元,是系统独立调度和分派CPU的基本单位指运行中的程序的调度单位。在单个程序中同时运行多个线程完成不同的工作,称为多线程。

2.什么是多线程?

在单个程序中同时运行多个线程完成不同的工作,称为多线程。

3.Java线程的实现
一种是实现Runnable接口
一种是继承Thread类

使用线程来控制plane.jpg图片的移动

import javax.swing.JFrame;

public class PlaneDemo extends JFrame implements Runnable {

    public static void main(String[] args) {
        PlaneDemo pd = new PlaneDemo();
        Thread t = new Thread(pd);
        t.start();
    }

    public PlaneDemo() {
        initUI();
    }

    private void initUI() {
        image = new ImageIcon(this.getClass().getResource("plane.jpg"))
                .getImage();
        this.setTitle("线程控制图片移动");
        this.setSize(600, 400);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(3);
        this.setResizable(false);
        this.setVisible(true);
        
        
    }

    private Image image;
    private int y = 300;

    /**
     * 重写窗体的paint方法
     */
    public void paint(Graphics g) {
        super.paint(g);

        g.drawImage(image, 250, y, 100, 100, this);
    }

    /**
     * 重写Runnable接口的run方法
     */
    public void run(){
        while(true){
            y-=3;
            if(y<=50)
                y = 300;
            
            repaint();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
原文地址:https://www.cnblogs.com/chang1203/p/5855086.html