一、在Java编程中罪常用的有两种创建线程的方式:继承thread类,重写run方法、实现runnable接口,实现run方法。
二、在这两种法法中,实现runnable的方法是比较好的,它只需要实现runnable接口,不影响其他类和其他接口,就像是让一个类多了线程的能力,体现了面向对象的思想。
三、demo 代码如下:
public class threadTest { public static void main(String[] args) { myThreadTest ms = new myThreadTest(); Thread thr = new Thread(ms); try { thr.start(); } catch (Exception e) { // TODO: handle exception } for(int j=0;j<10;j++){ try { Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception } System.out.println(j); } } } class myThreadTest implements Runnable{ public void run(){ for(int i=0;i<10;i++){ try { Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception } System.out.println("这是第" + i + "个线程"); } } }
四、输出如下:
0 这是第0个线程 1 这是第1个线程 2 这是第2个线程 这是第3个线程 3 4 这是第4个线程 5 这是第5个线程 6 这是第6个线程 7 这是第7个线程 8 这是第8个线程 9 这是第9个线程也欢迎登录我的个人网站,里面有更多的文章及技术咨询在等你:http://www.guangmuhua.com