I have an idea how to do this with AspectJ. The solution that I set out below will allow you to pause / resume another thread. This pause will take effect when you call the next method from your target method after calling the pause procedure. This will not require logical checks after each line of code of your target method. I use wait / notify for this.
I am using Spring in the example below.
First roll up your target method in Runnable.
package com.app.inter.thread.communication.runnables; public class TestRunnable implements Runnable{ public void run() { long i=0;
Then you will create an aspect that will be conditionally called when the method is called inside your target method.
@Aspect @Component public class HandlerAspect { public static volatile boolean stop=false; public static volatile String monitor=""; @Pointcut("withincode(public void com.app.inter.thread.communication.runnables.TestRunnable.run()) " + "&& call(* *.*(*)) " + "&& if()") public static boolean stopAspect(){ return stop; } @Before("stopAspect()") public void beforeAdvice(JoinPoint jp) { try { System.out.println("Waiting"); synchronized(monitor){ monitor.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } stop=false; } }
Now that you want to pause your stream, just set the stop value to true, and vice versa.
@Service public class Driver { @Autowired private HandlerAspect aspect; @PostConstruct public void init(){ Scanner scanner = new Scanner(System.in); int i=-1; TestRunnable runnable = new TestRunnable(); Thread thread= new Thread(runnable); thread.start(); aspect.monitor="MONITOR"; while((i=scanner.nextInt())!=0){ switch(i){ case 1: aspect.stop=true; break; case 2: aspect.stop=false; synchronized(aspect.monitor){ aspect.monitor.notify(); } break; } }
The output is as follows:
... Working 400000001 1Working 410000001 Working 420000001 Working 430000001 Working 440000001 Working 450000001 Working 460000001 Working 470000001 Waiting 2 Working 480000001 Working 490000001 0
The working code is at https://github.com/zafar142007/InterThreadCommunication
source share