Java实现多线程

Java多线程是指在一个程序中同时运行多个线程,每个线程独立执行不同的任务。在Java中,有两种方法可以实现多线程:

1. 继承Thread类

2. 实现Runnable接口

 

使用多线程可以提高程序的执行效率,充分利用CPU资源。下面是一个简单的Java多线程代码例子:

// 方法一:继承Thread类

class MyThread extends Thread {

    @Override

    public void run() {

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

            System.out.println("线程" + this.getName() + ":" + i);

        }

    }

}

 

public class Main {

    public static void main(String[] args) {

        MyThread thread1 = new MyThread();

        MyThread thread2 = new MyThread();

        thread1.start();

        thread2.start();

    }

}

// 方法二:实现Runnable接口

class MyRunnable implements Runnable {

    @Override

    public void run() {

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

            System.out.println("线程" + Thread.currentThread().getName() + ":" + i);

        }

    }

}

 

public class Main {

    public static void main(String[] args) {

        MyRunnable runnable = new MyRunnable();

        Thread thread1 = new Thread(runnable);

        Thread thread2 = new Thread(runnable);

        thread1.start();

        thread2.start();

    }

}

 

以上两个例子中,我们创建了两个线程并启动它们。每个线程都会打印0到9的数字。通过多线程,我们可以让这两个任务同时进行,提高程序的执行效率。 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值