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


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){ }
}
}
}

优质内容筛选与推荐>>
1、覆盖与隐藏
2、高手教你15分钟掌握JavaScript面向对象编程
3、XML与TreeView
4、Jenkins用户权限管理
5、微服务之springboot 自定义配置(一)Application配置文件


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号