如何在Java中同时调用方法? [英] How can I call methods simultaneously in Java?

查看:230
本文介绍了如何在Java中同时调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为自己所在的类编写Java程序,但我需要能够一次执行6个方法.我不知道该怎么做,但这只是我的一小部分:

I need to make a program in Java for a class I am in, but I need to be able to make 6 methods execute at once. I have no idea how to go about this, but here is a small bit of what I have:

public static void main(String[] args) {
    method1();
    method2();
    method3();
    method4();
    method5();
    method6();
}

这一次只播放一种方法,而我一次需要它们.

This just plays the methods one at a time, and I need them all at once.

推荐答案

使用多个线程,但是如果要从多个线程编辑相同的对象,则应该阅读并发性知识.

Make use of multiple threads, although you should read up on concurrency if you're going to edit the same objects from multiple threads.

public static void main(String[] args) {
    new Thread() { 
        public void run() {
            method1();
        }
    }.start();
    new Thread() { 
        public void run() {
            method2();
        }
    }.start();
    //etc

    //or, as kingdamian42 pointed out, if you use java8, use this
    new Thread(() -> method1()).start();
    new Thread(() -> method2()).start();
}

这篇关于如何在Java中同时调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆