如何在java中为不同的线程分配不同的方法 [英] How to assign different methods to different threads in java

查看:174
本文介绍了如何在java中为不同的线程分配不同的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对'C'中的线程有所了解,但在Java中我是新手。如果我想创建三个线程,一个用于加法,第二个用于减法,第三个用于乘法我可以简单地执行

I know a bit about threads in 'C' but am new to them in Java. If I want to create three threads, one for addition, second for subtraction and third for multiplication I can simply do

pthread_t mathThread[3];

在创建每个线程时,我可以在参数中为它们分配不同的函数。

and while creating each thread I can assign them different functions in their arguments.

void *add(void *arg);
void *sub(void *arg);
void *mul(void *arg);

在Java中,如果我实现Runnable接口,则只有一个运行( )我可以使用的方法。我如何实现上述内容?

In Java, if I implement the Runnable interface there is only one run() method that I can use. How do I implement the above?

推荐答案

创建三个不同的runnable:

Create three different runnables:

Runnable[] runnables = new Runnable[] {
  new Runnable() {
    public void run() { /* add code here */ }
  },
  new Runnable() {
    public void run() { /* sub code here */ }
  },
  new Runnable() {
    public void run() { /* mul code here */ }
  },
};

这篇关于如何在java中为不同的线程分配不同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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