Node:Multi threaded example, Next:Another multi threaded example (Prolog top level), Previous:Single threaded example, Up:Calling Prolog from Java
Following is a Java version of the train
example.
See Train, for information about how the train.sav
file is
created.
This is a multi threaded version of the train
example.
In this mode several threads can access the SICStus runtime via a
Prolog interface
. The static method Jasper.newProlog()
returns an object which implements a Prolog interface
. A thread
can make queries by calling the query-methods of the Prolog object.
The calls will be sent to a separate server thread which does the
actual call to SICStus runtime.
import se.sics.jasper.Jasper; import se.sics.jasper.Query; import se.sics.jasper.Prolog; import java.util.HashMap; public class MultiSimple { class Client extends Thread { Prolog jp; String qs; Client(Prolog p,String queryString) { jp = p; qs = queryString; } public void run() { HashMap WayMap = new HashMap(); try { synchronized(jp) { Query query = jp.openPrologQuery(qs, WayMap); try { while (query.nextSolution()) { System.out.println(WayMap); } } finally { query.close(); } } } catch ( Exception e ) { e.printStackTrace(); } } } MultiSimple(String argv[]) { try { Prolog jp = Jasper.newProlog(argv,null,"train.sav"); Client c1 = new Client(jp,"connected('Orebro', 'Hallsberg', Way1, Way1)."); c1.start(); // The prolog variable names are different from above so we can tell // which query gives what solution. Client c2 = new Client(jp,"connected('Stockholm', 'Hallsberg', Way2, Way2)."); c2.start(); } catch ( Exception e ) { e.printStackTrace(); } } public static void main(String argv[]) { new MultiSimple(argv); } }
Prolog
object jp
is the interface to SICStus. It
implements the methods of interface Prolog
, making it possible
to write quite similar code for single threaded and multi threaded
usage of Jasper.
The static method Jasper.newProlog()
returns such an object.
Jasper.newProlog
is the .sav
file to restore.
Two threads are then started, which will make different queries with
the connected
predicate.
openQuery
and the closing of the
query in a single synchronized block, synchronizing on the Prolog
object.