期末考试活下来的我终于鸽了好久,准备更下一篇文章了
这次,我们来看看线程。
线程
一、何为线程?
线程,有时被称为轻量进程(Lightweight Process,LWP),是程序执行流的最小单元。一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。(以上来自百度百科)
线程是一个复合体,详情大家可以再操作系统这门课中学到。为了方便理解,我个人把线程理解为一种分支。
二、结合事例演示
2.1基础演示
假如有这样一个程序,点击一下就有一个小球在点击处沿直线运动(如果csdn能发动图就好了,QAQ)
这种情况就是,点击一下瞬间出现结束状态,看不到中间过程,而且只有等当前绘图结束下才可以开始下一个绘制,但是,如果我们用了线程就不一样啦
2.2完整演示
首先,实现线程,要实现一个为Runnable的借口,重写他的run方法
我们的例子以一次画四个小球为例。每次点击即可开始下一次绘制。
import java.awt.Graphics;
import javax.swing.JFrame;
public class showUI {
public void UI(){
JFrame frame=new JFrame();
frame.setLocationRelativeTo(null);
frame.setSize(600, 400);
Listener th=new Listener();
mythread myth=new mythread();
frame.addMouseListener(th);
frame.setVisible(true);
Graphics g = frame.getGraphics();
th.setG(g);
myth.setG(g);
}
public static void main(String args[]){
showUI ui=new showUI();
ui.UI();
}
}
import java.awt.Color;
import java.awt.Graphics;
public class mythread **implements Runnable**{
static Graphics g;
public void setG(Graphics g){
this.g=g;
}
public void run() {
// TODO Auto-generated method stub
int i,choice,c,d;
int Place[]=new int[4];
for(i=0;i<4;i++)
{
Place[i]=(int)(Math.random()*1000%500);
}
choice=(int)(Math.random()*100%4);
c=(int)(Math.random()*100%50)-25;
d=(int)(Math.random()*100%50)-20;
for( i = 0;i<200;i++){
try {
int b=(int)(Math.random()*1000)%4;
//System.out.println(b);
if(b==0)
g.setColor(Color.black);
if(b==1)
g.setColor(Color.blue);
if(b==2)
g.setColor(Color.GREEN);
if(b==3)
g.setColor(Color.orange);
Thread.sleep(20);//每次运行之间控制为20ms,做出动态的感觉
} catch (InterruptedException e1) {
e1.printStackTrace();
}
g.fillOval(Place[choice]+i+c, Place[choice]-i+d, 20, 20);
}
}
}
//大家不要看这个代码有点长,其实就是随机生成四个小球,这个都不重要,重要的是下
//一个
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Listener extends MouseAdapter{
Graphics g;
public void setG(Graphics g){
this.g=g;
}
public void mouseClicked(MouseEvent e){
// mythread.run();
mythread th1=new mythread();//将实现Runnable的类实例化
mythread th2=new mythread();
mythread th3=new mythread();
mythread th4=new mythread();
Thread t1=new Thread(th1);//Thread是系统提供的线程类,生命对象,将要调用类的对象最为参数
Thread t2=new Thread(th2);
Thread t3=new Thread(th3);
Thread t4=new Thread(th4);
t1.start();//不能显示调用run()方法,只能调用start()方法
t2.start();
t3.start();
t4.start();
}
}
大体的效果感觉就是这样,我知道这很丑
以上就是线程的最基础的演示,如果有机会,我将给大家从头写线程弹球。(其实我还有很多,五子棋啊,画图板啊,魔塔小游戏啊(最近正在肝),很多可以分享的,毕竟我讲的还是比较细的对吧)。
我是咕咕咕咕咕士奇,不知道应该大概也许有下期再见