线程的实现方式

2014-11-24 02:03:54 · 作者: · 浏览: 0

多线程的两种实现方式,第一种继承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!");

}

}