创建线程的方法有2种:
一:继承thread类,重写 Thread 类的 run 方法; 二:实现Runnable接口,实现run方法;
实现Runnable接口,避免了继承Thread类的单继承局限性。覆盖Runnable接口中的run方法,将线程任务代码定义到run方法中。
//继承thread类
public class ThreadDemo { public static void main(String[] args) { My d = new My("d"); My d2 = new My("d2"); d.run();//没有开启新线程, 在主线程调用run方法 d2.start();//开启一个新线程,新线程调用run方法 } } class My extends Thread { //继承Thread My (String name){ super(name); } //复写其中的run方法 public void run(){ for (int i=1;i<=20 ;i++ ){ System.out.println(Thread.currentThread().getName()+",i="+i); } } }
//实现Runnable接口
public class Demo03 { public static void main(String[] args) { //创建线程执行目标类对象 Runnable runn = new MyRunnable(); //将Runnable接口的子类对象作为参数传递给Thread类的构造函数 Thread thread = new Thread(runn); Thread thread2 = new Thread(runn); //开启线程 thread.start(); thread2.start(); for (int i = 0; i < 10; i++) { System.out.println("main线程:正在执行!"+i); } } } //自定义线程执行任务类 class MyRunnable implements Runnable{ //定义线程要执行的run方法逻辑 @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("我的线程:正在执行!"+i); } } }
//创建Thread类的对象,只有创建Thread类的对象才可以创建线程。线程任务已被封装到Runnable接口的run方法中,而这个run方法所属于Runnable接口的子类对象,所以将这个子类对象作为参数传递给Thread的构造函数,这样,线程对象创建时就可以明确要运行的线程的任务。
- Thread.currentThread()获取当前线程对象;
- Thread.currentThread().getName();获取当前线程对象的名称;
调用run方法和start方法的区别:
调用线程的start方法是创建了新的线程,在新的线程中执行。
调用线程的run方法是在主线程中执行该方法,和调用普通方法一样,
线程的匿名内部类使用:
方式1:创建线程对象时,直接重写Thread类中的run方法
package thread; public class Demo04 { public static void main(String[]args){ new Thread() { public void run() { for (int x = 0; x < 40; x++) { System.out.println(Thread.currentThread().getName()+ "...X...." + x); } } }.start(); } }
方式2:使用匿名内部类的方式实现Runnable接口,重新Runnable接口中的run方法
Runnable r = new Runnable() { public void run() { for (int x = 0; x < 40; x++) { System.out.println(Thread.currentThread().getName() + "...Y...." + x); } } }; new Thread(r).start();