创建多线程的四种方式

注:主要记录创建的步骤,代码仅供参考

方式一:继承Thread

复制代码
/**
 * 创建多线程方式一:继承Thread
 * 1:创建一个继承于Thread类的子类
 * 2:重写Thread类的run()
 * 3:创建Thread类的子类对象
 * 4:通过此对象调用start()
 */
public class ThreadTestOne {
    public static void main(String[] args) {
        MyThread myThread1 = new MyThread();
        MyThread myThread2 = new MyThread();
        myThread1.start();
        myThread2.start();
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}
复制代码

方式二:实现Runnable接口

复制代码
/**
 * 创建多线程的方式二:实现Runnable接口
 * 1:创建一个实现了Runnable接口的类
 * 2:实现类去实现Runnable中的抽象方法:run()
 * 3:创建实现类的对象
 * 4:将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
 * 5:通过Thread类的对象调用start()
 */
public class ThreadTestTwo {
    public static void main(String[] args) {
        MThread mThread = new MThread();
        Thread thread = new Thread(mThread);
        thread.setName("进程一");
        thread.start();
        Thread thread2 = new Thread(mThread);
        thread2.setName("进程二");
        thread2.start();
    }
}

class MThread implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}
复制代码

方式三:实现Callable接口

复制代码
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 多线程创建方式之三:实现Callable接口。jdk5.0新增
 * 1:创建一个实现Callable的实现类
 * 2:实现call方法,将此线程需要执行的操作声明在call方法中
 * 3:创建Callable接口实现类的对象
 * 4:将此Callable接口实现类的对象作为参数传递到FutureTask构造器中,创建FutureTask的对象
 * 5:将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象并调用start()
 * 6:使用FutureTask的get方法获取Callable中call方法的返回值(可不获取)
 */
public class ThreadTestThree {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThirdThread thirdThread = new ThirdThread();
        FutureTask futureTask = new FutureTask(thirdThread);
        Thread thread = new Thread(futureTask);
        thread.setName("线程一");
        thread.start();
        for (int i = 1; i <= 100; i++) {
            if (i % 2 != 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }

        Object o = futureTask.get();
        System.out.println(Thread.currentThread().getName() + ": 线程一总和为" + o);
    }
}

class ThirdThread implements Callable {
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
                sum += i;
            }
        }
        return sum;
    }
}
复制代码

方式四:线程池

复制代码
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 创建多线程方式之四:线程池
 * 1:提供线程池
 * 2:执行指定的线程操作,需提供Runnable或Callable的实现类对象
 * 3:关闭线程池
 */
public class ThreadTestFour {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        //获取接口的实现类型
        //System.out.println(executorService.getClass());
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executorService;
        //设置线程池的属性
        threadPoolExecutor.setCorePoolSize(12);
        threadPoolExecutor.setMaximumPoolSize(10);
        /**
         * executorService.execute(Runnable commd);
         * executorService.submit(Callable commd):可用FutureTask获取结果;
         */
        executorService.submit(new ThreadTest());
        executorService.submit(new ThreadTest());
        executorService.shutdown();
    }
}

class ThreadTest implements Callable {
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
                sum += i;
            }
        }
        return sum;
    }
}
复制代码

 例:三个窗口同时售票

复制代码
public class ThreadRunnableLearn {
    public static void main(String[] args) {
        RunnableThread runnableThread = new RunnableThread();
        Thread thread1 = new Thread(runnableThread);
        thread1.setName("窗口一");
        Thread thread2 = new Thread(runnableThread);
        thread2.setName("窗口二");
        Thread thread3 = new Thread(runnableThread);
        thread3.setName("窗口三");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class RunnableThread implements Runnable {
    private int ticket = 100;

    @Override
    public void run() {
        while (true) {
            /**
             * 解决线程安全问题有三种方式:
             * 一:同步代码块(如例),RunnableThread类也是一个对象,而且只会加载一次,所以是唯一的
             * 二:同步方法【private synchronized void 方法名() {}】当操作共享数据的代码在一个方法中,则可使用
             * 当同步方法为非静态:则默认同步监视器是this
             * 当同步方法为静态: 则默认同步监视器是该方法属于的类 xxx.class
             * 三:ReentrantLock
             */
            synchronized (RunnableThread.class) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "售票,票号为" + ticket);
                    ticket--;
                }else {
                    break;
                }
            }
        }
    }
}
复制代码

 


posted @   Java厨师长  阅读(1500)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示