怎样理解java多对多_Java 对多线程的理解

对两种多线程的对比:

// Runnable 就是一个接口,Thread类实现了Runnable,Runnable存在解决只能单继承Thread的问题。

//因为Thread也实现了Runnable接口 且Runnable接口中只存在一个Run方法

// 因此,无论是implements Runnable还是 extendsThread都要实现run方法

// 只是如果是直接继承Thread类,当我们调用多线程的时候可以直接.start()

// 如果是通过实现Runnable接口,那么需要实例化Thread类来调用.start()

// Runnable 接口更适合于多个线程处理统一资源

26ddf0c44fe9ace64bd0f4c200479fb2.png

1、直接继承Thread类

package com.temp;

/**

* @Author lanxiaofang

* @email 983770299@qq.com

* @date 2020/12/5 13:08

*/

public class P205_07_Thead{

public static void main(String[] args) {

TestThread testThread1 = new TestThread("1");

TestThread testThread2 = new TestThread("2");

testThread1.start();

testThread2.start();

System.out.println("main is ending");

}

}

class TestThread extends Thread{

private String name;

public TestThread(String name){

this.name = name;

}

@Override

public void run() {

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

try {

sleep((int)(1000*Math.random()));

} catch (InterruptedException interruptedException) {

interruptedException.printStackTrace();

System.out.println(interruptedException);

}

System.out.println(name + " is Running "+i);

}

}

}

2、实现Runnable接口

package com.temp;

/**

* @Author lanxiaofang

* @email 983770299@qq.com

* @date 2020/12/5 14:35

*/

public class P207_08_Runnablr {

public static void main(String[] args) {

TestThread2 testThread2 = new TestThread2("testThread2");

TestThread2 testThread21 = new TestThread2("testThread21");

Thread thread1 = new Thread(testThread2);

Thread thread2 = new Thread(testThread21);

thread1.start();

thread2.start();

}

}

class TestThread2 implements Runnable{

private String name;

public TestThread2(String name){

this.name = name;

}

@Override

public void run() {

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

try {

Thread.sleep((int)(1000*Math.random()));

} catch (InterruptedException interruptedException) {

interruptedException.printStackTrace();

System.out.println(interruptedException);

}

System.out.println(name+" is running "+i);

}

}

}

标签:Runnable,Java,name,Thread,理解,new,多线程,public,TestThread

来源: https://blog.csdn.net/c_lanxiaofang/article/details/110780925

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值