创建线程的两种方式:
1继承thread类,
步骤
1定义类继承thread
2复写thread类中的run方法,目的:将自定义的代码存储在run方法,让线程运行
3调用该线程的start方法,该方法两个作用:启动线程,调用run方法。(此时线程处于runnable状态),从而使线程启动去同其他线程一起去强度cpu资源执行权(获取到CPU资源后就变成run状态)。
2 实现runnable接口,
步骤:
1定义类实现runnable接口
2 覆盖runnable接口中的run方法(将线程要运行的代码存放在run方法中)
3 通过thread类建立线程对象
4 将实现runnable接口的子类对象作为实际参数传入线程对象的构造方法中(创建线程对象的时候就要明确要运行的代码)。
此处为什么这样做?--》因为自定义的run方法所属的对象是runnable接口的子类对象,所以要让线程去执行指定对象的run方法,就必须明确该run方法所属的对象。
5调用thread类的start方法开启线程并调用runnable接口子类的run方法。
两种方式的区别:
1 继承thread类 线程代码存放在子类的run方法中
2 实现runnable接口 线程代码存放在实现runnable接口的子类的run方法中。(较常用)
线程子类调用 start方法后出现交替打印(主线程与thdo线程互相抢夺CPU资源)
package ThreadDemo1;
/* anthor lnw
* thread继承类的run与start对比
* */
public class demo1 {
public static void main(String[] args) {
ThreadDemo thdo=new ThreadDemo();//创建一个线程,但是还没执行
// thdo.run();//仅仅是对象调用方法,而线程创建了并没有执行run方法
thdo.start();//开启线程并执行该线程的run方法
for(int i=0;i<5;i++){
System.out.println("main-"+i );
}
}
}
class ThreadDemo extends Thread{
public void run(){
for(int i=0;i<5;i++){
System.out.println("demo"+i+" ");
}
}
}
方式二的使用:
package ThreadDemo1;
public class demo3 {
public static void main(String[] args) {
threadDemos thd=new threadDemos();
Thread th1=new Thread(thd);
Thread th2=new Thread(thd);
th1.start();
th2.start();
for(int i=0;i<10;i++){
System.out.println("main run"+i);
}
}
}
class threadDemos implements Runnable{
public void run(){
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"run"+i);
}
}
}
如何调整线程名称:
由于ThreadDem2类是thread类的子类,在thread类 API中获取线程名称可以通过getName()获取,修改可通过 Thread(String name)
分配新的Thread
对象,都是对基类thread的操作,所以子类可以通过this.getName()获取,通过子类构造函数ThreadDem2(String name){super(name)//基类API;}
package ThreadDemo1;
/*
*
* 注意此处的super()的使用
*
* */
public class demo2 {
public static void main(String[] args) {
ThreadDemo2 thd1=new ThreadDemo2("one+");
ThreadDemo2 thd2=new ThreadDemo2("two+");
thd1.start();
thd2.start();
for(int i=0;i<100;i++){
System.out.println("main run.."+i);
}
}
}
class ThreadDemo2 extends Thread{
ThreadDemo2(String name){
super(name);
}
public void run(){
for(int i=0;i<100;i++){
System.out.println(this.getName()+"run--"+i);
}
}
}