在Java中,可以使用多線程并發(fā)調(diào)用接口的方法有以下幾種方式:
public class MyRunnable implements Runnable {
private MyInterface myInterface;
public MyRunnable(MyInterface myInterface) {
this.myInterface = myInterface;
}
@Override
public void run() {
myInterface.method();
}
}
public interface MyInterface {
void method();
}
public static void main(String[] args) {
MyInterface myInterface = new MyInterfaceImpl();
MyRunnable myRunnable = new MyRunnable(myInterface);
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
thread1.start();
thread2.start();
}
public class MyThread extends Thread {
private MyInterface myInterface;
public MyThread(MyInterface myInterface) {
this.myInterface = myInterface;
}
@Override
public void run() {
myInterface.method();
}
}
public interface MyInterface {
void method();
}
public static void main(String[] args) {
MyInterface myInterface = new MyInterfaceImpl();
MyThread myThread1 = new MyThread(myInterface);
MyThread myThread2 = new MyThread(myInterface);
myThread1.start();
myThread2.start();
}
注意,在多線程并發(fā)調(diào)用接口的方法時(shí),需要注意對(duì)共享資源的同步訪問,以避免出現(xiàn)線程安全問題??梢允褂胹ynchronized關(guān)鍵字或其他同步機(jī)制來實(shí)現(xiàn)線程安全。