gpt4 book ai didi

java - 如何在两个线程之间来回切换

转载 作者:行者123 更新时间:2023-12-01 04:47:49 24 4
gpt4 key购买 nike

我在两个不同的类中有两个方法,就像这样

public class ClassX implements Runnable {

public void methodAandB() {
for(int i=0;i<10;i++) {
System.out.println("This is A and B ");
}
}
@Override
public void run() {
methodAandB();
}
}
<小时/>
public class ClassY implements Runnable {

public void methodAorB() {
for(int i=0;i<10;i++) {
System.out.println("This is A or B");
}
}

@Override
public void run() {
methodAorB(a);
}
}

线程t1正在调用methodAandB()

线程t2正在调用methodAorB()

<小时/>

我可以在方法中的每次循环迭代后在这两个线程之间切换吗?

我想得到这样的输出:

This is A and B

This is A or B

This is A and B

This is A or B

This is A and B

This is A or B

This is A and B

This is A or B

最佳答案

线程之间触发器的最佳示例:

给定两个 int 数组(偶数和奇数),2 个线程按自然顺序打印它们的数字。

package com.rough;

public class ThreadsBehaviour {

static Object lock = new Object();

public static void main(String[] args) throws InterruptedException {

int a[] = {1,3,5,7,9};
int b[] = {2,4,6,8,10};

Thread odd = new Thread(new Looper(a, lock));
Thread even = new Thread(new Looper(b, lock));

odd.start();
even.start();
}

}

class Looper implements Runnable
{

int a[];
Object lock;

public Looper(int a[], Object lock)
{
this.a = a;
this.lock = lock;
}
@Override
public void run() {

for(int i = 0; i < a.length; i++)
{
synchronized(lock)
{

System.out.print(a[i]);
try
{
lock.notify();
if(i == (a.length - 1))
{
break;
}
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}

}

关于java - 如何在两个线程之间来回切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15530484/

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