线程,是程序执行的最小单位。
一个线程必须处于如下四种可能的状态之一,这四种状态为:
初始态:一个线程调用了new方法之后,并在调用start方法之前的所处状态。在初始态中,可以调用start和stop方法。
Runnable:一旦线程调用了start 方法,线程就转到Runnable 状态,注意,如果线程处于Runnable状态,它也有可能不在运行,这是因为还有优先级和调度问题。 阻塞/ NonRunnable:线程处于阻塞/NonRunnable状态,这是由两种可能性造成的:要么是因挂起而暂停的,要么是由于某些原因而阻塞的,例如包括等待IO请求的完成。 退出:线程转到退出状态,这有两种可能性,要么是run方法执行结束,要么是调用了stop方法。
最后一个概念就是线程的优先级,线程可以设定优先级,高优先级的线程可以安排在低优先级线程之前完成。一个应用程序可以通过使用线程中的方法setPriority(int),来设置线程的优先级大小。
什么是进程?
进程,系统进行资源分配和调度的基本单位。
线程和进程的区别是什么?
一个程序至少有一个进程,一个进程至少有一个线程,线程的划分尺度小于进程。
实现线程的两种方法:(摘自百度百科)
1、就是通过继承Thread类的方式时,线程类就无法继承其他的类来实现其他一些功能,实现接口的方式就没有这中限制;
2.也是最重要的一点就是,通过实现Runnable接口的方式可以达到资源共享的效果。
什么是多线程?
多线程是这样一种机制,它允许在程序中并发执行多个指令流,每个指令流都称为一个线程,彼此间互相独立。
什么是并发编程?
所谓并发编程是指在一台处理器上“同时”处理多个任务。并发是在同一实体上的多个事件。多个事件在同一时间间隔发生。
package 线程;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GameUI extends JFrame {
private int x;//小球移动横坐标
private int y;//小球移动纵坐标
GameThread gt;//线程对象
public void initUI() {
this.setTitle("我大木叶村的基情对对碰");//设置窗体标题
this.setSize(500, 400);//设置窗体大小
this.setDefaultCloseOperation(3);//设置关闭
this.setLocationRelativeTo(null);//设置窗体居中
this.setLayout(new FlowLayout());//设置窗体布局
this.setResizable(false);//窗体大小不可调
ImageIcon ima = new ImageIcon("image/0.jpg");//设置背景图片
JLabel imgLabel1 = new JLabel(ima);//把图片添加到标签上
this.add(imgLabel1);//把标签加到窗体上
this.setVisible(true);//设置窗体可见
Graphics g = this.getGraphics();//获取画笔
gt = new GameThread(this);
gt.start();//启动线程
gt.setG(g);//传递画笔
}
//重绘方法
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.PINK);//设置画笔颜色
ImageIcon ima=new ImageIcon("image/1.png");//创建图标对象
g.drawImage(ima.getImage(),gt.getX(), gt.getY(), null);//画图像
}
public static void main(String[] args) {
GameUI game = new GameUI();
game.initUI();
}
}
package 线程;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class GameThread extends Thread{
private int x=1,y=1;//给横纵坐标初始值
private int movex=2 ,movey=2;//每次坐标改变的值得大小
JFrame jf;
private Graphics g;//接收传递过来的画笔对象
public void setG(Graphics g){//获取画笔的方法
this.g=g;
}
public int getX(){//获取横坐标
return x;
}
public int getY(){//获取纵坐标
return y;
}
public GameThread(JFrame jf){//构造方法传递窗体
this.jf=jf;
}
public void run(){//重写RUN方法
while(true){//使小球一直移动
//使小球碰到边弹回
if(y>jf.getHeight()-80)
movey=-movey;
if(x>jf.getWidth()-80)
movex=-movex;
if(x<1)
movex=-movex;
if(y<1)
movey=-movey;
try{
Thread.sleep(20);//线程休眠20毫秒
x+=movex;//改变坐标使小球移动
y+=movey;
}
catch(Exception e){//抛出异常
e.printStackTrace();
}
//调用重绘方法
jf.paint(jf.getGraphics());
}
}
}