本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
多线程的几种实现方法
奔跑的男人 · 527浏览 · 发布于2019-08-08 +关注

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

 


相关推荐

PHP实现部分字符隐藏

沙雕mars · 1325浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 908浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 970浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 962浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1086浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
分类专栏
小鸟云服务器
扫码进入手机网页