线程的创建方式

创建线程的方式 一:
继承Thread,重写run方法,run方法中的代码就是需要让线程并发执行的代码

public class ThreadDemo1 {
public static void main(String[] args) {
Thread ta = new MyThread1();
Thread tb = new MyThread2();

     // 启动线程要调用线程的start方法,而不需要直接调用run方法!
    // start方法调用完毕后,run方法会很快的被调用.
    ta.start();
    tb.start();
}

}

/**
* 这种创建线程方式的不足
* 1:由于java是单继承的,这就导致若继承了Thread当前类就无法继承其他类来复用方法
* 2:由于在当前类内部重写run方法,这就导致线程与其要执行的任务有一个必然的耦合关系.不利于
* 线程复用.
*/
class MyThread1 extends Thread{
public void run(){
for(int i=0;i<5000;i++){
System.out.println(“线程一”);
}
}
}
class MyThread2 extends Thread{
public void run(){
for(int i=0;i<5000;i++){
System.out.println(“线程二”);
}
}
}
// 创建线程的方式二:
// 实现Runnable接口并重写run方法来单独定义线程

public class ThreadDemo2 {
public static void main(String[] args) {
//创建线程要执行任务
Runnable rc = new MyRunnable3();
Runnable rd = new MyRunnable4();

    // 创建线程
    Thread tc = new Thread(rc);
    Thread td = new Thread(rd);
    tc.start();
    td.start();
}

}

class MyRunnable3 implements Runnable{
public void run() {
for(int i=0;i<5000;i++){
System.out.println(“线程三”);
}
}
}
class MyRunnable4 implements Runnable{
public void run() {
for(int i=0;i<5000;i++){
System.out.println(“线程四”);
}
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值