我正在尝试创建3个子线程,父线程必须显示1-5个数字,子线程1必须显示6-10,子线程2必须显示11-15,子线程3必须显示15-20...
这必须使用父类中的一个for循环和子类中的一个for循环来完成。类C是父类,类D是子类
public class C {
public static void main(String[] args){
D d = new D();
System.out.println(Thread.currentThread().getName());
Thread child1= new Thread(d);
Thread child2= new Thread(d);
Thread child3= new Thread(d);
child1.start();
child2.start();
child3.start();
for(int i=1; i<=5;i++){
System.out.println("From parent thread: " +i);
}
}
public class D extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}发布于 2016-01-22 08:22:23
Java为并发编程/多线程(MT)问题提供了一个有趣的解决方案。在"java.concurrent“资源中,有一种特殊类型的对象,称为锁。因为你的问题有点模糊(可能是家庭作业),所以我只能给你一个基本的答案。无论如何,"lock“对象提供了线程相互通信所需的工具。我还会看看委托( MT问题的一种常见的CS解决方案)。
锁定:https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html
https://stackoverflow.com/questions/34936598
复制相似问题