当前位置:编程学习 > JAVA >>

线程的实现方式

 

多线程的两种实现方式,第一种继承Thread类,第二种实现Runnable接口。

方式一(继承Thread类):

Java代码 

package com.demo.thread; 

 

public class ThreadDemo1 extends Thread 

    private int count = 5; 

     

    // 只初始化一次 

    private static int threadCount = 0; 

     

    private int threadNumber = ++threadCount; 

     

    public ThreadDemo1() 

    { 

        System.out.println("Making" + threadNumber); 

    } 

     

    public void run() 

    { 

        while (true) 

        { 

            System.out.println("Thread" + threadNumber + "(" + count + ")"); 

            if (--count == 0) 

            { 

                return; 

            } 

        } 

    } 

     

    public static void main(String[] args) 

    { 

        for (int i = 0; i < 5; i++) 

        { 

            new ThreadDemo1().start(); 

        } 

        System.out.println("All threads started!"); 

    } 

 

方式二(实现Runnable接口):

Java代码 

package com.demo.thread; 

 

public class ThreadDemo2 implements Runnable 

    private int count = 5; 

     

    private static int threadCount = 0; 

     

    private int threadNumber = ++threadCount; 

     

    public ThreadDemo2() 

    { 

        System.out.println("Making" + threadNumber); 

    } 

     

    public void run() 

    { 

        while (true) 

        { 

            System.out.println("Thread" + threadNumber + "(" + count + ")"); 

            if (--count == 0) 

            { 

                return; 

            } 

        } 

         

    } 

     

    public static void main(String[] args) 

    { 

        for (int i = 0; i < 5; i++) 

        { 

            ThreadDemo2 td = new ThreadDemo2(); 

            new Thread(td).start(); 

        } 

        System.out.println("All Threads started!"); 

    } 

}   

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,