gpt4 book ai didi

Java 线程与对象

转载 作者:行者123 更新时间:2023-12-01 17:34:09 25 4
gpt4 key购买 nike

假设我有一个包含排序数字列表的类。

该对象有一个 get 函数,因此我可以看到类内的私有(private)变量(在本例中为数组)

如果我对对象进行线程化,我如何访问类的 get 函数?

eg
Thread t1 = new testclass();
t1.start();
t1.getvalue() ; ??

我还没有编写任何代码,仍处于作业的设计阶段

最佳答案

通常,在 Java 中,人们使用 Runnable而不是从 Thread 派生:

class MyThing implements Runnable {
private int x;
public void run() {
x = 10;
}
public int getX() { return x; }
}

MyThing thing = new MyThing();
Thread t = new Thread(thing);
t.start(); // The thread starts and calls MyThing::run() in itself
t.join(); // wait for t to finish
System.out.println(t.getX());

除了接口(interface)之外,Runnable 没有什么特别之处——您可以轻松地直接调用 thing.run(),只不过它会运行在你自己的线程。

关于Java 线程与对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8102821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com