您的位置:首页 > 编程语言 > Java开发

JAVA中建立多线程的典型例子

2006-02-16 21:48 281 查看
JAVA中建立多线程,无非两种方式,一是继承自thread类,另一种是实现runnable接口,下面两个例子很典型,可以复习下
1、继承自thread类

public class j02140301 extends Thread // 步骤 1
{
public void run() // 步骤 2 ,覆盖继承自 Thread 的 run()
{
while(true)
{
System.out.print("X ");
//....
try
{
Thread.sleep(1000); // 此线程要休眠 1 秒
}
catch(InterruptedException e){/*...*/}
}
}

public static void main(String abc[])
{
Thread ThreadObj1 = new myDog();
ThreadObj1.start(); // 自动调用 run()

Thread ThreadObj2 = new j02140301();
ThreadObj2.start(); // 自动调用 run()

for(int x=1;x<=5;x++)// main thread 执行此 for 叙述句
{
System.out.print("A ");
}
System.out.println();
} //到此 main thread 就停了
}

//=======================================================
//另一个继承 Thread 的类
class myDog extends Thread // 步骤 1
{
public void run() // 步骤 2
{
System.out.print("dog ");
}
}

2、public class j02140302 implements Runnable // 步骤 1
{
public void run() // 步骤 2
{
while(true)
{
System.out.println("欢迎~~ ");
//....
try
{
Thread.sleep(1000); // 休眠 1000 毫秒
}
catch(InterruptedException e){ }
}
}

public static void main(String abc[])
{
Thread ThreadObj1 = new Thread( new welcome() ); // 步骤 3 ,利用 Runnable 对象建构 Thread 对象
ThreadObj1.start(); // 步骤 4 自动调用 welcome 实现的 run()

Thread ThreadObj2 = new Thread( new j02140302() ); // 步骤 3 ,利用 Runnable 对象建构 Thread 对象
ThreadObj2.start(); // 步骤 4 自动调用 j02140302 实现的 run()
}
}

class myFriend
{
public void sayHello()
{
System.out.println("朋友!好久不见!");
}
}

class welcome extends myFriend implements Runnable // 步骤 1
{ //拥有 myFriend 的实例,也有 Runnable 的实例
public void run() // 步骤 2
{
while(true)
{
sayHello();
try
{
Thread.sleep(3000); // 休眠 3000 毫秒
}
catch(InterruptedException e){ }
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: