Thread and runnable

java 实现多线程两种方式
     1.继承threaa类
  2.实现runnable 接口

thread其实是runnable的一种实现
通过调用thread.start(),会通过jvm找到run()方法,启动


runable 好处 避免点继承的局限,一个类可以继承多个接口

thread code:

public static void main(String[] args) {
        MyThread thread1 = new MyThread("thread one");
        MyThread thread2 = new MyThread("thread two");

        thread1.start();
        thread2.start();
    }

    public static class MyThread extends Thread{
        private String name;
        public MyThread(String name) {
            super();
            this.name = name;
        }
        public void run(){
            for(int i=0;i<10;i++){
                System.out.println("线程开始:"+this.name+",i="+i);
            }
        }
    }

runnable code:

    public static void main(String[] args) {
        MyRunnable runnableOne = new MyRunnable("one");
        MyRunnable runnableTwo = new MyRunnable("two");

        new Thread(runnableOne).start();
        new Thread(runnableTwo).start();
    }

    public static class MyRunnable implements Runnable {
        private String name;

        public MyRunnable(String name) {
            this.name = name;
        }

        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println("runable run:" + this.name + ",i=" + i);
            }
        }
    }

 

参考:

http://blog.csdn.net/sunguangran/article/details/6069317

 

posted @ 2013-10-24 19:30  Jsaint  阅读(118)  评论(0)    收藏  举报