如何让线程并发执行?我有下面的代码。处理T.Create(mt);在c.Consume(mt)开始之前完成它的整个任务。我在T.Create(mt)中放了一个睡眠功能;函数,但c.Consume(mt)在完成之后仍然不会启动。我正在尝试使用create process将对象添加到堆中,并使用consume进程从堆中删除它们,以便它们撤消彼此的工作。
package javaapplication2;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JavaApplication2 {
public static void main(String[] args) {
NewThread T = new NewThread();
T.start();
NewThread c = new NewThread();
c.start();
MinHeap mt = new MinHeap(50);
T.Create(mt);
c.Consume(mt);
}
class NewThread extends Thread
{
NewThread()
{
}
public void run(MinHeap minHeap)
{
}
public void Create(MinHeap minHeap)
{
Random rand = new Random();
int randNum = rand.nextInt(40) + 1;
System.out.println("num = " + randNum);
int i =0;
Node n = new Node();
n.setID(randNum);
minHeap.first(n);
while (minHeap.getSize() < 15)
{
n = new Node();
randNum = rand.nextInt(40) + 1;
n.setID(randNum);
minHeap.insert(n);
System.out.print("Input: " + randNum + " Heap = ");
minHeap.print();
try{Thread.sleep(800);}catch(Exception e){}
}
minHeap.print();
minHeap.remove();
System.out.println("========= size = " + minHeap.getSize());
minHeap.print();
}
public void Consume(MinHeap minHeap)
{
while (minHeap.getSize() > 0)
{
System.out.print("Consume - Heap = ");
minHeap.remove();
minHeap.print();
try{Thread.sleep(800);}catch(Exception e){}
}
}
}
答案 0 :(得分:2)
首先,发布可以在任何其他人的计算机上运行的代码(尽可能少的代码量)是个好主意,这样我们就可以更好地调试您的问题。
这些链接可能有所帮助:
答案 1 :(得分:1)
您需要在线程的Create()
方法中执行Consume
和run()
方法。因为现在以通常的串行方式调用T.Create()
和c.consume()
。