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();
        }

    }
}

猜你喜欢

转载自blog.csdn.net/u012614287/article/details/69819350