zoukankan      html  css  js  c++  java
  • Thread 与 Runnable 混合使用测试

    package com.dava;
    
    public class TesThread extends Thread implements Runnable {
        public void run() {
            System.out.println("运行成功!");
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            Thread t=new Thread(new TesThread());
            t.start();
    
        }
    
    }

    运行结果:

    运行成功!

    程序继承了Thread 实现Runnable,接口的方法是需要全部实现的,而Runnable接口源码如下:

    public
    interface Runnable {
        /**
         * When an object implementing interface <code>Runnable</code> is used 
         * to create a thread, starting the thread causes the object's 
         * <code>run</code> method to be called in that separately executing 
         * thread. 
         * <p>
         * The general contract of the method <code>run</code> is that it may 
         * take any action whatsoever.
         *
         * @see     java.lang.Thread#run() 
         */
        public abstract void run();
    }
    

     所以有run();方法程序会正常执行.

    单独继承Runnable方法:

    public class ImpInterface implements Runnable {
        
        public void run() {
            // TODO Auto-generated method stub
    
        }
        /**
         * @param args
         */
        public static void main(String[] args) {
            System.out.println("123465");
        }
    
    }

    如果部实现run方法会出现异常。但是在上面的ji集成了Thread又实现了Runnable,可以部实现Run方法,程序会正常运行。

    package com.dava;
    
    public class TesThread extends Thread implements Runnable {
    //    public void run() {
    //        System.out.println("运行成功!");
    //    }
        public void print() {
            System.out.println("1231456");
    
        }
        /**
         * @param args
         */
        public static void main(String[] args) {
            
    //        Thread t=new Thread(new TesThread());
    //        t.start();
            new TesThread().print();
            
    
        }
    
    }

    运行结果:1231456

    为什么不实现接口也行呢?看下图

    Thread也实现了Runnable接口,实现了Run方法,子类默认继承了父类的方法,所以也实现了Runnable的run方法。

  • 相关阅读:
    POJ:1185-炮兵阵地(状压dp入门)
    LightOj:1422-Halloween Costumes
    HDU:4632-Palindrome subsequence
    POJ:2955-Brackets(经典:括号匹配)
    POJ:2342-Anniversary party(树形dp入门题目)
    HUD:2853-Assignment(KM算法+hash)
    HDU:2255-奔小康赚大钱(KM算法模板)
    POJ:3020-Antenna Placement(二分图的最小路径覆盖)
    POJ:3041-Asteroids(匈牙利算法模板)
    SVN
  • 原文地址:https://www.cnblogs.com/dava/p/6675758.html
Copyright © 2011-2022 走看看