Java多线程实现方式(实现源码)

1.继承thread类

public class MTPingIP extends Thread{
    private String ip;

    public MTPingIP(String ip) {
        this.ip = ip;
    }

    /**
     * 重写Run方法
     * 执行业务代码
     */
    @Override
    public void run() {
        //PingIP.pingIP(ip);
        for (int i = 0; i <10; i++) {
            //返回正在执行的线程实例
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName()+"ping的ip为:"+ip+i);
        }
    }
}

2.实现Runnable接口

public class MTPingIPRunnable implements Runnable{
    /**
     * 重写run方法
     * 业务代码
     */
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName()+"执行打印:"+i);
        }
    }
}

3.实现Callable接口

public class MTCallable implements Callable {
    /**
     * 重写call方法
     * 业务代码
     * @return
     * @throws Exception
     */
    @Override
    public Object call() throws Exception {
        for (int i = 0; i < 10; i++) {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName()+"执行打印:"+i);
        }
        return 123;
    }
}

4.线程池的使用

//定义线程池类
public class MTPool implements Runnable{
    /**
     * 重写run方法
     * 业务函数
     */
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName()+"执行打印:"+i);
        }
    }
}
=======================================================================================

    @Test
    public void testMTPool(){
        //实例化线程池类
        MTPool mtPool = new MTPool();
        //使用Executors创建固定长度为4的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //调用execute启动线程
        executorService.execute(mtPool);
        executorService.execute(mtPool);
        executorService.execute(mtPool);
    }

测试类

    //继承thread类 实现多线程
    @Test
    public void test1(){
       new MTPingIP("192.168.31.").start();
       new MTPingIP("192.168.30.").start();
       new Thread(new MTPingIP("192.168.29")).start();
    }

    //实现Runnable接口 实现多线程
    @Test
    public void test2(){
        MTPingIPRunnable mtPingIPRunnable = new MTPingIPRunnable();
        new Thread(mtPingIPRunnable,"阿奇").start();
        new Thread(mtPingIPRunnable,"二傻").start();
    }

    //实现Callable接口 实现多线程
    @Test
    public void test3(){
        FutureTask futureTask = new FutureTask(new MTCallable());
        FutureTask futureTask1 = new FutureTask(new MTCallable());
        new Thread(futureTask,"阿奇").start();
        new Thread(futureTask1,"二傻").start();
    }


版权声明:本文为alone_song原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。