在Java中为线程添加其他方法?
我想我可以通过尝试这样的方法来实现,但它不起作用:在Java中为线程添加其他方法?,java,multithreading,algorithm,concurrency,Java,Multithreading,Algorithm,Concurrency,我想我可以通过尝试这样的方法来实现,但它不起作用: Thread[] threads = new Thread[myNumThreads]; for (int i=0; i<myNumThreads; i++) { threads[i] = new Thread () { @Override public void run() { <Code to do when running> } /
Thread[] threads = new Thread[myNumThreads];
for (int i=0; i<myNumThreads; i++) {
threads[i] = new Thread () {
@Override
public void run() {
<Code to do when running>
}
//CODE I TRIED TO ADD:
public boolean getValue(){
return true;
}
};
}
Thread[]threads=新线程[myNumThreads];
对于(int i=0;i而言,当您运行代码时,它始终使用当前线程。如果代码附加到另一个线程对象,例如thread.join();则在后台线程运行时,等待的仍然是当前线程
让另一个线程执行工作的最简单方法是使用ExecutorService
ExecutorService es = Executors.newFixedThreadPool(myNumThreads);
List<Future<ResultType>> futures = new ArrayList<>();
for (int i = 0; i < myNumThreads; i++) {
futures.add(es.submit(new Callable<Result>() {
public ResultType call() {
// do something
return result;
}
});
}
// do something while the thread task executes
for (Future<ResultType> future: futures) {
ResultType result = future.get();
}
// when finished with the pool
es.shutdown();
Executors=Executors.newFixedThreadPool(myNumThreads);
列表期货=新的ArrayList();
for(inti=0;i
您可以尝试编写自己的线程:比如“MyThread扩展线程”很难理解您所说的“它不工作”是什么意思,但我认为您可能只是错过了对
threads[i].start();
但是,如果您希望能够从类外部调用getValue()方法,则需要创建一个新的MyThread类,该类扩展Thread并使用该类型而不是Thread:
class MyThread extends Thread {
@Override
public void run() {
for (int j=0 ; j< 10; j++) {
System.out.println("working:" + j + ":" + this.getValue());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//CODE I TRIED TO ADD:
public boolean getValue(){
return true;
}
}
类MyThread扩展线程{
@凌驾
公开募捐{
对于(int j=0;j<10;j++){
System.out.println(“工作:+j+:“+this.getValue());
试一试{
睡眠(1000);
}捕捉(中断异常e){
e、 printStackTrace();
}
}
}
//我试图添加的代码:
公共布尔getValue(){
返回true;
}
}
然后按如下方式进行命名:
int myNumThreads = 10;
MyThread[] threads = new MyThread[myNumThreads];
for (int i=0; i<myNumThreads; i++) {
threads[i] = new MyThread () ;
threads[i].start();
}
System.out.println(threads[0].getValue());
intmynumthreads=10;
MyThread[]threads=新的MyThread[myNumThreads];
对于(int i=0;iTalk about-“但它不起作用。”调用join()
不会结束线程,它允许调用方等待被加入的线程“结束”,直到线程“结束”为止。线程不能返回任何内容。它可以做的是更新其他线程可见的某些对象。在线程之间共享内容的最简单方法是使用全局(即,static
)变量。[注意:static
如果在大型软件系统中使用,会给您带来痛苦,但在小型一次性程序中会节省时间。]线程之间共享的一种非常有用的对象是队列
:(一个线程,称为“生产者”),将结果放入队列,另一个线程“消费者”将其取出。)现在尝试一下,让我们看看结果如何。他理解我的答案,正在尝试,所以我认为它是正确的。回答不错!我相信该方法名为newFixedThreadPool
-而不是newFixedSizePool
。是的,这就是我现在尝试的方法。