多线程几种常用方法代码

线程只能start一次
1.sleep,休眠

//增加事故发生问题
public class TestSleep implements Runnable{
    //票
    private int ticketNum=10;
    @Override
    public void run() {
        while(true){
            if(ticketNum<=0){
                break;
            }

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"---拿到了票:"+ticketNum--);
        }
    }

    public static void main(String[] args) {
        TestThread4 testThread4=new TestThread4();
//可用共同资源
        new Thread(testThread4,"张三").start();
        new Thread(testThread4,"李四").start();
        new Thread(testThread4,"王五").start();
    }
}

2.yield(),礼让,当前线程出来,在公平竞争

//出来就是公平竞争,礼让不会一定成功
public class TestYield {
    public static void main(String[] args) {
        MyYield myYield=new MyYield();

        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();
    }

}
class MyYield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始");
        Thread.yield();//礼让,重新竞争
        System.out.println(Thread.currentThread().getName()+"线程结束");
    }
}

3.join()插队vip

//插队vip,可能会阻严重
public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("vip插队"+i);
        }
    }

    public static void main(String[] args) {
        TestJoin testJoin=new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

        for (int i = 0; i < 20; i++) {
            if(i==10){
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("main线程"+i);
        }

    }

}

4.stop终止线程

//1.次数
// 2.标志位
//3.不建议使用stop,story,等
public class TestStop implements Runnable{
    //1.设置标志位
    private boolean flag=true;
    @Override
    public void run() {
        int i=0;
        while (flag){
            System.out.println("run...Thread"+i++);
        }
    }
//2.停止线程的方法,转换标志位
    public void stop(){
        this.flag=false;
    }

    public static void main(String[] args) {

        TestStop testStop=new TestStop();

        new Thread(testStop).start();
        for (int i = 0; i < 2000; i++) {
            System.out.println("main"+i);
            if(i==1990){
                //调用标志位转换,停止
                testStop.stop();
            }
        }
    }
}

5.getState(),setState()获取线程状态

//观测状态
public class TestState {
    public static void main(String[] args) {
        Thread thread=new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("///////");
        });

        //观察状态
        Thread.State state=thread.getState();
        System.out.println(state);//new

        thread.start();
        state=thread.getState();//run
        System.out.println(state);

        //线程不终止
        while(state!=Thread.State.TERMINATED){//终止的静态变量
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            state=thread.getState();//更新!!!
            System.out.println(state);
        }
        //线程只执行一次,不会两次start()
//        thread.start();
    }
}

6.setPriority,设置优先级

public class TestYield {
    public static void main(String[] args) {
        MyYield myYield=new MyYield();

        Thread thread = new Thread(myYield, "a");

        Thread thread1 = new Thread(myYield, "b");
        thread.setPriority(10);
        thread1.setPriority(1);
        thread.start();
        thread1.start();
    }

}
class MyYield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程");

    }
}

运行结果经常是:

a线程
b线程

因为优先级1-10,默认5,数字越大,越容易运行,当然也不绝对。

在编程中,实现多线程的方式因语言和框架的不同而有所差异。以下是一些常见的实现方法和技术: ### Java 中的多线程实现方法 1. **继承 `Thread` 类** 通过创建一个继承自 `Thread` 类的子类并重写其 `run()` 方法,可以在新的线程中执行特定的任务。调用 `start()` 方法启动线程,JVM 会自动调用 `run()` 方法[^3]。 ```java class MyThread extends Thread { public void run() { // 执行任务的代码 } } MyThread thread = new MyThread(); thread.start(); // 启动线程 ``` 2. **实现 `Runnable` 接口** 另一种常见方式是实现 `Runnable` 接口,并将其传递给 `Thread` 对象。这种方式更灵活,因为它允许将任务与线程分离[^1]。 ```java class MyRunnable implements Runnable { public void run() { // 执行任务的代码 } } Thread thread = new Thread(new MyRunnable()); thread.start(); // 启动线程 ``` 3. **使用 `ExecutorService` 框架** Java 提供了高级的并发工具类库,如 `ExecutorService`,可以管理多个线程并分配任务[^1]。 ```java ExecutorService executor = Executors.newFixedThreadPool(5); executor.submit(() -> { // 执行任务的代码 }); executor.shutdown(); // 关闭线程池 ``` 4. **使用 `Callable` 和 `Future`** 与 `Runnable` 不同,`Callable` 允许返回结果并抛出异常。可以通过 `Future` 获取异步计算的结果[^1]。 ```java Callable<Integer> task = () -> { // 返回计算结果 return 123; }; Future<Integer> future = executor.submit(task); Integer result = future.get(); // 阻塞直到结果可用 ``` ### Qt 中的多线程实现方法 1. **使用 `QThread`** `QThread` 是 Qt 提供的底层 API,用于创建和管理线程。它支持事件循环,适用于复杂的线程管理场景[^2]。 ```cpp class Worker : public QObject { Q_OBJECT public slots: void doWork() { // 执行任务的代码 } }; QThread* thread = new QThread; Worker* worker = new Worker(); worker->moveToThread(thread); connect(thread, &QThread::started, worker, &Worker::doWork); connect(worker, &Worker::finished, thread, &QThread::quit); connect(worker, &Worker::finished, worker, &Worker::deleteLater); connect(thread, &QThread::finished, thread, &QThread::deleteLater); thread->start(); ``` 2. **使用 `QtConcurrent`** `QtConcurrent` 提供了一种简单的方式来并行执行任务,适用于不需要复杂线程管理的场景[^2]。 ```cpp auto future = QtConcurrent::run([]() { // 执行任务的代码 }); ``` ### C++ 中的多线程实现方法 1. **使用 `std::thread`** C++11 引入了标准线程库 `std::thread`,可以直接创建和管理线程[^4]。 ```cpp void threadFunction() { // 执行任务的代码 } std::thread t(threadFunction); t.join(); // 等待线程完成 ``` 2. **使用互斥锁(`mutex`)和条件变量(`condition_variable`)** 在多线程环境中,互斥锁和条件变量用于保护共享资源并协调线程之间的通信[^4]。 ```cpp std::mutex mtx; std::condition_variable cv; bool ready = false; void waitFunction() { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, []{ return ready; }); // 继续执行任务 } void notifyFunction() { { std::lock_guard<std::mutex> lock(mtx); ready = true; } cv.notify_all(); } std::thread t1(waitFunction); std::thread t2(notifyFunction); t1.join(); t2.join(); ``` 3. **使用 `std::async` 和 `std::future`** `std::async` 可以异步执行任务,并通过 `std::future` 获取结果[^4]。 ```cpp auto future = std::async(std::launch::async, []() { // 返回计算结果 return 123; }); int result = future.get(); // 阻塞直到结果可用 ``` 4. **原子操作(`std::atomic`)** 原子操作确保某些操作在多线程环境下不会被中断,避免了数据竞争问题[^4]。 ```cpp std::atomic<int> counter(0); void incrementCounter() { for (int i = 0; i < 1000; ++i) { counter++; } } std::thread t1(incrementCounter); std::thread t2(incrementCounter); t1.join(); t2.join(); ``` ### 总结 不同的编程语言和框架提供了多种实现多线程方法,开发者可以根据具体需求选择合适的方式。Java 提供了从基础到高级的多种工具,Qt 则通过 `QThread` 和 `QtConcurrent` 实现多线程编程,而 C++ 则利用标准库中的线程、互斥锁、条件变量等机制来处理并发任务。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值