java多线程基础实例代码

多线程是java的一个重要特性,在网络编程中常会用到。java中实现多线程主要有继承Thread类实现Runnable接口两种方法。可以直接运行的示例代码如下:

继承Thread类

主要包括以下几个step:
step1.继承Thread类,重写run方法。
step2.创建Thread数组。
step3.创建并启动每个Thread对象。

//多线程执行类
public class MyThread extends Thread {

    private int index; //用于向线程运行程序输入参数。通过构造器方法输入

    public MyThread(int index){
        this. index = index;
    }
    public void run (){
        for(int i = 0;i < 10;i ++){
            try {
                Thread.sleep(200);
            }catch(InterruptedException e ){
                continue;
            }
            System.out.println("thread:"+ index+ ":do things no."+i);
        }
    }
}
//多线程调用类
class TestThread{
    public static void main(String[] args){
        MyThread [] myThreads = new MyThread[100];
        for(int seq = 0; seq < 100; seq ++){
            myThreads[seq] = new MyThread(seq);
            myThreads[seq].start();
        }
    }
}

实现Runnable接口

主要包括以下几个step:
step1.实现Runnable接口,重写run方法。
step2.创建Runnable和Thread数组。
step3.传入实现Runnbale接口的类,创建并启动每个Thread对象。

//多线程执行类
public class MyRunnable implements Runnable{

    private int index;//用于向线程运行程序输入参数。通过构造器方法输入

    public MyRunnable( int index){
        this. index = index;
    }
    @Override
    public void run() {
        for(int i = 0;i < 10;i ++){
            try {
                Thread.sleep(200);
            }catch(InterruptedException e ){
                continue;
            }
            System.out.println("thread:"+ index+ ":do things no."+i);
        }
    }
}
//多线程调用类
class TestRunnable{
    public static void main(String[] args){
        MyRunnable[] myRunnables = new MyRunnable[100];
        Thread[] threads = new Thread[100];
        for(int seq = 0;seq < 100;seq ++){
            myRunnables[seq] = new MyRunnable(seq);
            threads[seq] = new Thread(myRunnables[seq]);
            threads[seq].start();
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值