我在两个不同的类中有两个方法,就像这样
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/