Java创建多线程的方法

多线程

​ Java 给多线程编程提供了内置的支持。 一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

多线程同一个时刻,可以执行多个线程,比如:一个qq进程,可以同时打开多个聊天窗口;一个迅雷进程,可以同时下载多个文件。

​ 在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。

代码实现方法

​ 下面使用两种方式打印10次hello,并输出线程名。

继承Thread的实现方式

public class Main {
    public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest();
        threadTest.start();
    }
}

class ThreadTest extends Thread{
    int count = 0;
    @Override
    public void run(){
        while (true) {
            count++;
            System.out.println("hello " + count + " threadName:" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count == 10) {
                break;
            }
        }
    }
}

运行结果

hello 1 threadName:Thread-0
hello 2 threadName:Thread-0
hello 3 threadName:Thread-0
hello 4 threadName:Thread-0
hello 5 threadName:Thread-0
hello 6 threadName:Thread-0
hello 7 threadName:Thread-0
hello 8 threadName:Thread-0
hello 9 threadName:Thread-0
hello 10 threadName:Thread-0

实现Runable接口的实现方式

注意:在这里不能直接调用run()方法

public class Main {
    public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest();
        Thread thread = new Thread(threadTest);
        thread.start();
    }
}

class ThreadTest implements Runnable{
    int count = 0;
    @Override
    public void run() {
        while (true) {
            count++;
            System.out.println("hello " + count + " threadName:" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count == 10) {
                break;
            }
        }
    }
}

运行结果

hello 1 threadName:Thread-0
hello 2 threadName:Thread-0
hello 3 threadName:Thread-0
hello 4 threadName:Thread-0
hello 5 threadName:Thread-0
hello 6 threadName:Thread-0
hello 7 threadName:Thread-0
hello 8 threadName:Thread-0
hello 9 threadName:Thread-0
hello 10 threadName:Thread-0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值