当前位置: 移动技术网 > IT编程>开发语言>Java > Java向Runnable线程传递参数方法实例解析

Java向Runnable线程传递参数方法实例解析

2020年06月13日  | 移动技术网IT编程  | 我要评论

滨崎步演唱会下载,妇女节的来历,上犹县

java runnable接口:是一个接口,它里面只有一个run()方法,没有start()方法,继2113承runnable并实现这个方法就可以实现多线程了,但是5261这个run()方法不能自4102己调用,必须由系统来调用。

向线程中传递数据的三种方法:

一、通过构造函数传递参数

public class mythread1 extends thread
{
  private string name;
  public mythread1(string name)
  {
    this.name = name;
  }
  public void run()
  {
    system.out.println("hello " + name);
  }
  public static void main(string[] args)
  {
    thread thread = new mythread1("world");
    thread.start();    
  }
}

二、通过变量和方法传递数据

public class mythread2 implements runnable
{
  private string name;
  public void setname(string name)
  {
    this.name = name;
  }
  public void run()
  {
    system.out.println("hello " + name);
  }
  public static void main(string[] args)
  {
    mythread2 mythread = new mythread2();
    mythread.setname("world");
    thread thread = new thread(mythread);
    thread.start();
  }
}

三、通过回调函数传递数据

class data
{
  public int value = 0;
}
class work
{
  public void process(data data, integer numbers)
  {
    for (int n : numbers)
    {
      data.value += n;
    }
  }
}
public class mythread3 extends thread
{
  private work work;
 
  public mythread3(work work)
  {
    this.work = work;
  }
  public void run()
  {
    java.util.random random = new java.util.random();
    data data = new data();
    int n1 = random.nextint(1000);
    int n2 = random.nextint(2000);
    int n3 = random.nextint(3000);
    work.process(data, n1, n2, n3);  // 使用回调函数
    system.out.println(string.valueof(n1) + "+" + string.valueof(n2) + "+"
        + string.valueof(n3) + "=" + data.value);
  }
  public static void main(string[] args)
  {
    thread thread = new mythread3(new work());
    thread.start();
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网