当前位置: 移动技术网 > IT编程>开发语言>Java > 多线程的学习一:创建多线程的方式

多线程的学习一:创建多线程的方式

2019年08月08日  | 移动技术网IT编程  | 我要评论

创建线程的方法有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();

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网