多线程
在我们的OS里,
进程是资源分配的最小单位
线程是cpu调度的最小单位
1、继承Thread
创建:AextendsThread
在A中实现run()
启动:利用继承自Thread的strart()方法
Aa=newA();
a.start();
2、实现Runnable接口
创建:AimplementsRunnable
在A中实现run()
启动:以A的对象为Thread的构造函数的参数创建Thread对象
并且利用它的start()方法调度启动线程
Aa=newA();
Threadb=newThread(a);
b.start();
3、利用TimerTimerTask
创建:创建TimerTask的子类,并实现run()方法得到时钟器任务类
MyTimerTaskextendsTimerTask{
publicvoidrun(){
}
}
启动:创建时钟器Timer对象
利用时钟器对象的schedule()方法启动线程任务
Timertimer=newTimer();
timer.schedule(newMyTimerTask(),....,...);
3种方法实现多线程:
importjava.util.Timer;
importjava.util.TimerTask;
publicclassMyFirstThreadTest{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
// MyThread1mt=newMyThread1();
// mt.start();
// MyThread2mt2=newMyThread2();
// Threadt=newThread(mt2);
MyThread3mt3=newMyThread3();
Timertimer=newTimer();
timer.schedule(mt3,3000,500);
for(inti=0;i<10;i++){
System.out.println("GoodMorning!!");
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
classMyThread1extendsThread{
publicvoidrun(){
for(inti=0;i<10;i++){
System.out.println("Helloworld");
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
classMyThread2implementsRunnable{
publicvoidrun(){
for(inti=0;i<10;i++){
System.out.println("Helloworld");
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
classMyThread3extendsTimerTask{
publicvoidrun(){
for(inti=0;i<10;i++){
System.out.println("Helloworld");
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}