当前位置:网站首页>Implement the runnable interface

Implement the runnable interface

2022-06-26 05:59:00 Mr.Rop

Realization Runnable Interface

//  Create thread 2:  Realization Runnable Interface , rewrite run() Method , The execution thread needs to drop runnable Interface implementation class , call start() Method .
public class TestThread3 implements Runnable {
    
    @Override
    public void run() {
    
        for (int i = 0; i < 100; i++) {
    
            // run Method thread body 
            System.out.println(" I'm looking at the code -----" + i);
        }
    }

    public static void main(String[] args) {
    
        //  establish Runnable Implementation class object of interface 
        TestThread3 testThread3 = new TestThread3();
        //  Create thread , Object starts a thread through a thread object 
// Thread thread = new Thread(testThread3);
// thread.start();

        new Thread(testThread3).start();
        
        for (int i = 0; i < 1000; i++) {
    
            System.out.println(" I'm learning multithreading -----" + i);
        }
    }
}

Summary

  • Inherit Threa class

    • A subclass inherits Thread Class has multithreading capabilities
    • Start thread : Subclass object .start()
    • Not recommended : avoid OOP Limitations of single inheritance
  • Realization Runnable Interface

    • Implementation interface Runnable Multithreading capability
    • Start thread : Incoming target object Thread object .start()
    • Recommended : Avoid the limitations of single inheritance , Flexible and convenient , It is convenient to unify an object to be used by multiple threads
原网站

版权声明
本文为[Mr.Rop]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180503012343.html