多线程篇一:传统线程实现方式

1.new 一个Thread子类(这里是一个内部类)通常写法如SubThread

复制代码
Thread thread=new Thread(){
 @Override
 public void run(){
      while(true){
          try {
                Thread.sleep(500);
                System.out.println("0:"+Thread.currentThread());
                System.out.println("1:"+this.currentThread());
               } catch (InterruptedException e) {
                    e.printStackTrace();
               }
           }
       }
 }; 
thread.start();
复制代码

SubThread

复制代码
package com.test.thread;

public class SubThread extends Thread{

    @Override
    public void run(){
        while(true){
            System.out.println("111111111111");
        }
    }
    
    public static void main(String[] args) {
        SubThread sub=new SubThread();
        sub.start();
    }
}
复制代码

2.new一个Runnable对象 ,面向对象的使用方式

复制代码
Thread thread2=new Thread(new Runnable(){
            @Override
            public void run(){
                while(true){
                    try {
                        Thread.sleep(500);
                        System.out.println("2:"+Thread.currentThread());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
  thread2.start();
复制代码

 

方法2通常写法如下

Thread thread3=new Thread(new SubRunable());
thread3.start();

复制代码
package com.test.thread;

public class SubRunable implements Runnable{

    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(500);
                System.out.println("SubRunable:"+Thread.currentThread());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
复制代码

 

posted @   陈小兵  阅读(224)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示