首页 > 代码库 > 传统线程实现方式
传统线程实现方式
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(); } } }}
传统线程实现方式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。