多线程的概念
程序与进程
程序:一段静态的代码。
进程:程序的一次动态执行过程,它对应从代码加载、执行到执行完毕的一个完整过程。
每个进程都是存在于内存空间中的一部分.
进程与线程
线程是比进程更小的执行单位,它是在一个进程中独立的控制流,即程序内部的控制流。
简单的说,两者是包含的关系,一个进程可以有多个线程.
线程类(Thread)
java.lang包中提供了一个专门的线程类(Thread),在该类中封装了许多对线程进行调度和处理的方法。
class类名extendsThread{
publicvoidrun(){
//线程体
}
}
在我们的OS里,进程是资源分配的最小单位,线程是cpu调度的最小单位
继承Thread
创建:AextendsThread
在A中实现run()
启动:利用继承自Thread的strart()方法
Aa=newA();
a.start();
实现Runnable接口
创建:AimplementsRunnable
在A中实现run()
启动:以A的对象为Thread的构造函数的参数创建Thread对象
并且利用它的start()方法调度启动线程
Aa=newA();
Threadb=newThread(a);
b.start();
利用TimerTimerTask
创建:创建TimerTask的子类,并实现run()方法得到时钟器任务类
MyTimerTaskextendsTimerTask{
publicvoidrun(){
}
}
启动:创建时钟器Timer对象
利用时钟器对象的schedule()方法启动线程任务
Timertimer=newTimer();
timer.schedule(newMyTimerTask(),....,...);
实现文字滚动的原理
abcdefg=a+bcdefg=>bcdefg+a
bcdefga
Cdefgab
类似于上面蚊子,如要实现文字滚动效果,可以让所有字符按顺序循环,即可做出滚动效果.例如:
publicclassWordsextendsFrame{
Labellb=newLabel("我爱北京!");
publicWords(){
super("");
this.add(lb);
this.setSize(100,200);
this.setVisible(true);
newMyThread(lb).start();
}
publicstaticvoidmain(String[]args){
newWords();
}
}
classMyThreadextendsThread{
Labellb=null;
publicMyThread(Label_lb){
lb=_lb;
}
publicvoidrun(){
Stringstr=lb.getText();
while(true){
inti=50;
i++;
try{
str=str.substring(1)+str.substring(0,1);
lb.setText(str);
Thread.sleep(20);
}catch(InterruptedExceptionie){
ie.printStackTrace();
}
for(;i<256;i+=16){
lb.setBackground(newColor(150,i,i));
try{
Thread.sleep(20);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
}
即可做出文字和背景颜色滚动效果.