Java Multithreading Example

This is not on the IB Computer Science syllabus, but it’s useful for IAs and Grade 10 projects. One of the key reasons you might decide to run some code in its own thread is so that your GUI can remain responsive to user-generated events like button clicks. Imagine you have a sudoku game that displays a timer. You would need to run the timer in its own thread so that the game remained responsive to the user entering answers in the sudoku grid.

public class MultiThreadingExample {

    public static void main(String[] args) {
        /* Create five new tasks and set them running in their
         * own threads.
         */
        for (int i = 0; i < 5; i++) {
            /* Notice that because we don't re-use the task 
             * or thread objects, there is no need to assign
             * them to variables. This code is equivalent to
             *
             * Task task = new Task();
             * Thread thread = new Thread(task);
             * thread.start()
             */
            (new Thread(new Task())).start();
        }
    }
}

class Task implements Runnable {
     
    private static int nextId;
    private int id;
    
    public Task() {
        init();
    }
    
    private synchronized void init() {
        /* The synchronized keyword ensures that any thread
         * that runs this method runs the whole method before
         * yielding to another thread. This is necessary here
         * to prevent two threads from executing id = nextId
         * consecutively (in which case they will both get the
         * same id).
         */
        id = nextId;
        nextId = nextId + 1;        
    }
    
    public void run() {
        /* Each thread just counts up to 10 and prints out its
         * id and the number it has reached.
         */
        for(int i = 0; i < 10; i++) {
            System.out.println(id + ": " + i);
        }
    }
}

Inserting Multiple Rows into a SQLite Database from Java

package sqlitetest;
import java.sql.*;

public class SqliteTest {

    public static void main(String args[]) {
        Connection connection = null;

        try {
            /* The next line will give a ClassNotFound error unless the
               sqlite jar is in the classpath. To add it in Netbeans, 
               right-click on the project, choose Properties, Libraries 
               and add the path to the jar file. On Linux I saved it in 
               /usr/local/sqlite/sqlite-jdbc-3.20.0.jar, but this will be
               different if you are using Mac or Windows.
            */
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:sqlite:test.db");

            // The database must already have a country table with these fields.
            // In my table there is also a CountryId primary key field, but the
            // database assigns values to that field automatically.
            String sql = "insert into Country (CountryName, Population) values (?, ?)";
            PreparedStatement ps = connection.prepareStatement(sql);


            // In larger applications you would probably loop through a list
            // of country objects. This is just a simple demo.

            ps.setString(1, "United States of America");
            ps.setString(2, "320000000");
            ps.addBatch();

            ps.setString(1, "China");
            ps.setString(2, "1400000000");
            ps.addBatch();

            ps.executeBatch();
            connection.close();

        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
        System.out.println("Insert successful");
    }
}

Simple chat server in Python

Add the following code to server.py and run.

# server.py
#!/usr/bin/python

import socket

sock = socket.socket()
host = 'localhost' # Change this to "" to receive connections from any host
port = 12221  # Any unreserved port but must be same as client
sock.bind((host, port))

sock.listen(5)
conn = None

while True:
   if conn is None:
       # Halts
       print ('[Waiting for connection...]')
       conn, addr = sock.accept()
       print('Got connection from', addr)
   else:
       # Halts
       print ( '[Waiting for response...]')
       print (conn.recv(1024))
       msg = input("Enter something to this client: ")
       conn.send(msg.encode('UTF-8'))

Add the following code to client.py.

# client.py
#!/usr/bin/python

import socket

sock = socket.socket()
host = 'localhost' # Change this to remote ip as necessary
port = 12221 # Any unreserved port but must be same as server

sock.connect((host, port))
print ('Connected to', host)

while True:
msg = input("Enter something for the server: ")
sock.send(msg.encode('UTF-8'))
# Halts
print ('[Waiting for response...]')
print (sock.recv(1024))

Code is STUFF

In English we distinguish between count nouns and non-count or mass nouns. Consider what feels wrong about these sentences:

  • My glass is full of waters.
  • I’ve got sands in my shoes.
  • Could I borrow a money?
  • I want to buy a furniture.

The reason these are wrong is that water, sand, money and furniture are examples of mass nouns. They are STUFF. You cannot pluralize stuff and you cannot refer to “a stuff”.

Why am I telling you this? Because “code”, as in lines of computer code, is also a mass noun. Code is STUFF. You cannot refer to “codes” and you cannot write “a code”.

Please try to remember this!

Java Serialization Example

Java provides a method of saving objects to file, called Serialization. In order for an object to be serializable it must implement the java.io.Serializable interface and you should set a version ID as well as shown below.

class Student implements java.io.Serializable {

   String name = "";
   Integer age = 0;
   Double gpa = 0.0;

   private static final long serialVersionUID = 1L;
}

You can save the object to file like this:

        try {
            FileOutputStream fileOut = new FileOutputStream(path);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(obj);
        } catch (IOException i) {
            i.printStackTrace();
        }

And you can load it like this:

        try {
            FileInputStream fileIn = new FileInputStream(path);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            obj = (Student)in.readObject();
        } catch (FileNotFoundException fnf) {
            System.out.println("No serialized file found at " + path + ". Creating new blank object.");
            obj = new Student();
        }
         catch (Exception e) {
            e.printStackTrace();
        }

Nested loops: looking for duplicates in arrays

A and B are arrays of integers. Construct code to output all of the values that are in both A and B.

With questions like this, imagine you had to do it manually. Imagine you have two long lists of numbers on paper. How would you find all the values that occur in both lists?

You would probably look at the first number from list A and then scan all the way down list B to see if it’s there. If it was you’d make a note of it. Then you would get the next number from list A and do the same thing.

A computer algorithm will do exactly the same thing.

In pseudocode this is:

loop I from 0 to A.length - 1
  loop J from 0 to B.length - 1
    if A[I] = B[J] then
      output A[I]
    end if
  end loop
end loop

In Java it is:

for (int i = 0; i < a.length; i++) {
  for (int j = 0; j < b.length; j++) {
    if (a[i] == b[j]) {
      System.out.println(a[i]);
    }
  }
}

Basic Java Class Structure

Basic knowledge for IB Computer Science is the structure of a Java class. You should be able to create the class, its instance variables, constructor, get and set methods, and a toString() method, without even need to stop and think.

Question:

Create a Point class that has two instance variables x and y, corresponding to its coordinates on the Cartesian plane. Include an appropriate constructor that initialises these variables. Encapsulate the variables and provide a toString() method.

Answer:

public class Point {
   private int x;
   private int y;

   public Point(int x, int y) {
       setX(x);
       setY(y);
   }

   public int getX() {
      return x;
   }

   public int getY() {
      return y;
   }

   public void setX(int x) {
      this.x = x;
   }

   public void setY(int y) {
      this.y = y;
   }

   public String toString() {
      return "(" + x + "," + y +")";
   }
}

Printing the numbers from 0 to 99

Students often get hung up on slight syntax differences, as if knowing how to program is the same as knowing a language’s syntax. It isn’t. Look at these examples and check you understand that they do the same thing. It is the logic of your programs that is important, not the brackets and semi-colons.

IB Computer Science pseudocode

loop J from 0 to 99
  output J
end loop

Python

for j in range(0,100):
  print(j)

Java

for (int j = 1; j < 100; j++) {
  System.out.println(j);
}