java - java连接两个线程

标签 java multithreading concurrency

我有两个扩展 Thread 的类。一类、二类。

在我的驱动程序类中,我创建了类一的三个线程和类二的一百个线程。

每个类一线程需要通知每个类二线程它可以进行交互。两个线程交互后,线程 One 会移动到另一个尚未与 One 类线程交互的类 Two 线程。

如何连接两种类型的线程?如何连接 1 类和 2 类线程。使用类 1 的线程如何让使用类 2 的每个线程知道它可以进行交互?

前代码:

public class Driver {
public static Semaphore sem = new Semaphore(1);


public static void main(String[] args) {
    // TODO Auto-generated method stub

    Teller tellerOne = new Teller(1);

    Teller tellerTwo = new Teller(2);

    Teller tellerThree = new Teller(3);

    tellerOne.start();
    tellerTwo.start();
    tellerThree.start();

    Client[] clients = new Client[10];

    for(int i = 0; i<10; i++){
        clients[i] = new Client(i);
        clients[i].start();
        }



    System.out.println("Bank closes");
    //end main method. do not write past this line
}




public class Teller extends Thread {

public int id;
public boolean bankOpen;
public Semaphore tsem;


Teller(int id){
    this.id = id;
}

public void run(){
    System.out.println("Teller " + id + " is available");



//end of run
}

//method to notify availability to client
public void notifyAvailabilityToClient(){

}


//end teller class, do not write past this line


public class Client extends Thread {

public int id;
public String status;
public Semaphore csem;


Client(int id){
    this.id = id;
}

public void run(){
    Random rand = new Random();
    int withdrawOrDeposit = rand.nextInt(100);
    withdrawOrDeposit = withdrawOrDeposit%2;
    //if wORd%2 = 0, withdraw, else deposit

    if(withdrawOrDeposit==0){
        status="Withdraw";
    }
    else{
        status="Deposit";
    }

    System.out.println("Client " + id + " waits in line to make a " + status);


//end of run method, do not write past this 
}

//method to select an open Teller
public void selectAvailableTeller(){


}

//end of client class, do not write past this line

顺便说一句,我可以使用类:信号量和线程

最佳答案

我通常不会编写不同线程相互相遇的代码,但由于这似乎是一项家庭作业......

在我的解决方案中,将有一个单一的阻塞队列。当“柜员”线程启动时,每次它完成与客户的“交互”时,它都会将自己放入队列中,然后等待新客户开始交互。顾客们都等着take()队列中的出纳员,当他们得到一个时,...与其“互动”。

<小时/>

如果不是家庭作业,我会做一些完全不同的事情。我不知道为什么“客户”线程是一件事,但我根本看不到“柜员”线程有任何用处。可能存在某种有限的可用性 Teller 对象,但它们不是线程。客户线程可以通过简单地调用Teller来“交互”。方法,或者如有必要,通过提交调用 Teller任务通用线程池的方法。

关于java - java连接两个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60871531/

相关文章:

java - Cloudera 内存不足,Java 运行时环境无法继续

java - 如何在运行时更改特定用户/线程的日志级别

ios - AFNetworking用于图像下载,UI无响应

Java - 使用 ConcurrentLinkedDeque 避免 NonSuchElementException

java - 启动tomcat时出现空指针异常

java - 使用 Java 进行身份验证的 HTTP 代理

c++ - 两个线程进入无限循环

java - 关于并发JAVA的建议

java - ExecutorService 在频繁关闭后导致内存不足异常

java - 无法获取两个日期之间的记录