Listing 1: Parallel Threads in Java

Thread t1 = new Thread (new Runnable() {
	public void run() { while(true) { System.out.println("tic"); }}
});
Thread t2 = new Thread (new Runnable() {
	public void run() { while(true) { System.out.println("toc"); }}
});

t1.start(); t2.start();



Listing 2: Pooled Parallel Threading in Java

ExecutorService svc = Executors.newCachedThreadPool();
Future tic[] = new Future[10], toc[] = new Future[10];
for (int i=0; i<10; i++) {
	tic[i] = svc.submit (new Runnable() {
		public void run() { for(int i=0; i<10; i++) System.out.println("tic"); }
	});
	toc[i] = svc.submit (new Runnable() {
		public void run() { for(int i=0; i<10; i++) System.out.println("toc"); }
	});
}

	try {
		for (int i=0; i<10; i++) {
			tic[i].get(); toc[i].get();
		}
	} catch (InterruptedException e1) {
		return;
	} catch (ExecutionException e2) {
		return;
	}



Listing 3: Synchronized Updates

public class Counter {
	private int ctr = 0;
	public synchronized void Increment(int k) { ctr += k; }
	public synchronized void Decrement(int k) { ctr -= k; }
}



Listing 4:  Atomic Increment

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicCounter {
	AtomicInteger ctr = new AtomicInteger(0);
	public void Increment(int k) { ctr.addAndGet(k); }
	public void Decrement(int k) { ctr.addAndGet(-k); }
}


Listing 5 : Wait and Notify

private Node top = null;

public synchronized void push (int x) {
	Node newNode = new Node(x,top);
	top = newNode;
	notify();
}

public synchronized int pop() {
	while (top == null) {
		try { wait(); }
		catch (InterruptedException e) { }
	}
	int result = top.data;
	top = top.next;
	return result;
}



Listing 6: Parallel tasks in X10

 while (true) {
   async System,out.println("tic");
   async System,out.println("toc");
 }



Listing 7: Atomic Increment in X10

   atomic ctr = ctr + 1;



Listing 8: Wait/Notify in X10

private nullable<Node> top = null;

public void push (int x) {
	Node newNode = new Node(x,top);
	Atomic top = newNode;
}

public int pop() {
	when (top != null) {
		int result = top.data;
		top = top.next;
		return result;
}
}