JAVA多线程机制

/**
 * 多线程
 * duoxianc可以并发执行多个代码片段,使得代码有机会“同时进行”。
 * <p>
 * 线程的创建有俩种方式:
 * 1:继承Thread并重写run方法
 */
public class ThreadDemo1 {
    public static void main(String[] args) {
     Thread thread=new MyThead1();
     Thread thread1=new MyThead2();
        Thread thread2=new MyThead3();
     /*
     启动线程要调用start方法,而不是直接调用run方法
     当启动start方法调用线程会纳入到线程调度器中,一旦获取到了
     时间片,run方法会自动被执行
      */
     thread.start();
     thread1.start();
     thread2.start();
    }
}

/**
 * 第一种创建线程的方式优点在于:结构简单,利于匿名内部类的创建
 * 缺点有俩个:
 * 1。继承Thread,由于是单继承,这导致如果继承了Threa就无法再
 * 继承其他类来复用代码,实际开发中很不方便
 * 2:定义线程的同重写了run方法来定义线程要定义的任务,这导致线程与
 * 线程要执行的任务存在这必然的绑定关系,不利于线程的重用
 */
class MyThead1 extends Thread {
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("你是谁!");
        }
    }
}

class MyThead2 extends Thread {
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("查水表的!");
        }
    }
}

class MyThead3 extends Thread {
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("开门没水了!");
        }
    }
}

第二种方式

package thread;

/**
 * 第二种
 */

public class ThreadDemo2 {
    public static void main(String[] args) {
        //单独定义线程任务
        Runnable r1=new MyRunable1();
        Runnable r2=new MyRunable2();
        //创建线程
        Thread t1=new Thread(r1);
        Thread t2=new Thread(r2);

        t1.start();
        t2.start();
    }
}
class MyRunable1 implements Runnable{
    public void run(){
        for (int i=9;i<10000;i++){
            System.out.println("来了老哥!");
        }
    }
}
class MyRunable2 implements Runnable{
    public void run(){
        for (int i=9;i<10000;i++){
            System.out.println("进来玩啊!");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ovideooos

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值