温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用Runnable实现并发控制

发布时间:2025-09-01 23:27:19 来源:亿速云 阅读:111 作者:小樊 栏目:编程语言

在Java中,Runnable接口是实现多线程的一种方式。要使用Runnable实现并发控制,你可以遵循以下步骤:

  1. 创建一个实现Runnable接口的类:
class MyRunnable implements Runnable {
    private int counter;

    public MyRunnable(int counter) {
        this.counter = counter;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            synchronized (this) {
                counter++;
            }
        }
    }

    public int getCounter() {
        return counter;
    }
}

在这个例子中,我们创建了一个名为MyRunnable的类,它实现了Runnable接口。我们在run()方法中递增一个计数器。为了实现并发控制,我们使用synchronized关键字来确保每次只有一个线程可以访问counter

  1. 创建并启动多个线程:
public class Main {
    public static void main(String[] args) throws InterruptedException {
        MyRunnable myRunnable = new MyRunnable(0);

        Thread thread1 = new Thread(myRunnable);
        Thread thread2 = new Thread(myRunnable);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("Counter: " + myRunnable.getCounter());
    }
}

在这个例子中,我们创建了两个线程thread1thread2,并将它们都指向同一个MyRunnable实例。然后我们启动这两个线程,并使用join()方法等待它们完成。最后,我们打印计数器的值。

由于我们使用了synchronized关键字来确保每次只有一个线程可以访问counter,因此最终的计数值将是预期的2000。如果没有使用synchronized关键字,计数值可能会小于2000,因为多个线程可能会同时访问和修改counter

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI