Monday, August 3, 2009

Ants





























Free JavaScripts provided

by The JavaScript Source



Clock

import java.applet.*;

import java.awt.*;

import java.util.*;


public class ClockApplet extends Applet implements Runnable{
Thread t,t1;
public void start(){
t = new Thread(this);
t.start();
}

public void run(){
t1 = Thread.currentThread();
while(t1 == t){
repaint();
try{
t1.sleep(1000);
}catch(InterruptedException e){}
}
}

public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 20, 30);
}
}

Calculator

/**
This is a simple calculator program can any one take and use.

@author sathish_ssmca
@param nothing */
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
//
public class Calculator extends JApplet {
public void init() {
CalculatorPanel calc=new CalculatorPanel();
getContentPane().add(calc);
}
}

class CalculatorPanel extends JPanel implements ActionListener {
JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
static JTextField result=new JTextField("0",45);
static String lastCommand=null;
JOptionPane p=new JOptionPane();
double preRes=0,secVal=0,res;

private static void assign(String no)
{
if((result.getText()).equals("0"))
result.setText(no);
else if(lastCommand=="=")
{
result.setText(no);
lastCommand=null;
}
else
result.setText(result.getText()+no);
}

public CalculatorPanel() {
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300,200);
add(result,BorderLayout.NORTH);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(4,4));

n7=new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8=new JButton("8");
panel.add(n8);
n8.addActionListener(this);
n9=new JButton("9");
panel.add(n9);
n9.addActionListener(this);
div=new JButton("/");
panel.add(div);
div.addActionListener(this);

n4=new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5=new JButton("5");
panel.add(n5);
n5.addActionListener(this);
n6=new JButton("6");
panel.add(n6);
n6.addActionListener(this);
mul=new JButton("*");
panel.add(mul);
mul.addActionListener(this);

n1=new JButton("1");
panel.add(n1);
n1.addActionListener(this);
n2=new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3=new JButton("3");
panel.add(n3);
n3.addActionListener(this);
minus=new JButton("-");
panel.add(minus);
minus.addActionListener(this);

dot=new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0=new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal=new JButton("=");
panel.add(equal);
equal.addActionListener(this);
plus=new JButton("+");
panel.add(plus);
plus.addActionListener(this);
add(panel,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==n1) assign("1");
else if(ae.getSource()==n2) assign("2");
else if(ae.getSource()==n3) assign("3");
else if(ae.getSource()==n4) assign("4");
else if(ae.getSource()==n5) assign("5");
else if(ae.getSource()==n6) assign("6");
else if(ae.getSource()==n7) assign("7");
else if(ae.getSource()==n8) assign("8");
else if(ae.getSource()==n9) assign("9");
else if(ae.getSource()==n0) assign("0");
else if(ae.getSource()==dot)
{
if(((result.getText()).indexOf("."))==-1)
result.setText(result.getText()+".");
}
else if(ae.getSource()==minus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="-";
result.setText("0");
}
else if(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText());
lastCommand="/";
result.setText("0");
}
else if(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText());
if(lastCommand.equals("/"))
res=preRes/secVal;
else if(lastCommand.equals("*"))
res=preRes*secVal;
else if(lastCommand.equals("-"))
res=preRes-secVal;
else if(lastCommand.equals("+"))
res=preRes+secVal;
result.setText(" "+res);
lastCommand="=";
}
else if(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText());
lastCommand="*";
result.setText("0");
}
else if(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="+";
result.setText("0");
}

}
}

Thursday, July 30, 2009

Second Synchronized Example

class TwoStrings {
static void print(String str1, String str2) {
System.out.print(str1);
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
System.out.println(str2);
}
}

class PrintStringsThread implements Runnable {
Thread thread;
String str1, str2;
TwoStrings ts;
PrintStringsThread(String str1, String str2, TwoStrings ts)
{
this.str1 = str1;
this.str2 = str2;
this.ts = ts;
thread = new Thread(this);
thread.start();
}
public void run() {
synchronized (ts) {
ts.print(str1, str2);
}
}
}

class TestThread {
public static void main(String args[]) {
TwoStrings ts = new TwoStrings();
new PrintStringsThread("Hello ", "there.", ts);
new PrintStringsThread("How are ", "you?", ts);
new PrintStringsThread("Thank you ", "very much!", ts);
}
}

Producer-Consumer Example

The following example is an implementation of the Producer-Consumer problem. A class which provides the methods for generating and consuming an integer value is separated from the Producer and the Consumer thread classes.

class SharedData {
int data;
synchronized void set(int value) {
System.out.println("Generate " + value);
data = value;
}
synchronized int get() {
System.out.println("Get " + data);
return data;
}
}

class Producer implements Runnable {
SharedData sd;
Producer(SharedData sd) {
this.sd = sd;
new Thread(this, "Producer").start();
}
public void run() {
for (int i = 0; i < 10; i++) {
sd.set((int)(Math.random()*100));
}
}
}

class Consumer implements Runnable {
SharedData sd;
Consumer(SharedData sd) {
this.sd = sd;
new Thread(this, "Consumer").start();
}
public void run() {
for (int i = 0; i < 10 ; i++) {
sd.get();
}
}
}

class TestProducerConsumer {
public static void main(String args[]) throws Exception {
SharedData sd = new SharedData();
new Producer(sd);
new Consumer(sd);
}
}

Here is a sample output of the program.

Generate 8
Generate 45
Generate 52
Generate 65
Get 65
Generate 23
Get 23
Generate 49
Get 49
Generate 35
Get 35
Generate 39
Get 39
Generate 85
Get 85
Get 85
Get 85
Generate 35
Get 35
Get 35

This is not what we wanted the program to do. For every value produced by the producer, we expect the consumer to get each value. Here is the output we expect instead.

Generate 76
Get 76
Generate 25
Get 25
Generate 34
Get 34
Generate 84
Get 84
Generate 48
Get 48
Generate 29
Get 29
Generate 26
Get 26
Generate 86
Get 86
Generate 65
Get 65
Generate 38
Get 38
Generate 46
Get 46

To fix the problem with this code, we use the methods for interthread communication.
The following implementation of the Producer-Consumer problem uses the methods for interthread communication.

class SharedData {
int data;
boolean valueSet = false;
synchronized void set(int value) {
if (valueSet) { //has just produced a value
try {
wait();
} catch (InterruptedException ie) {
}
}
System.out.println("Generate " + value);
data = value;
valueSet = true;
notify();
}
synchronized int get() {
if (!valueSet) { //producer hasn't set a value yet
try {
wait();
} catch (InterruptedException ie) {
}
}
System.out.println("Get " + data);
valueSet = false;
notify();
return data;
}
}

/* The remaining part of the code doesn't change. */
class Producer implements Runnable {
SharedData sd;
Producer(SharedData sd) {
this.sd = sd;
new Thread(this, "Producer").start();
}
public void run() {
for (int i = 0; i < 10; i++) {
sd.set((int)(Math.random()*100));
}
}
}

class Consumer implements Runnable {
SharedData sd;
Consumer(SharedData sd) {
this.sd = sd;
new Thread(this, "Consumer").start();
}
public void run() {
for (int i = 0; i < 10 ; i++) {
sd.get();
}
}
}

class TestProducerConsumer {
public static void main(String args[]) throws Exception {
SharedData sd = new SharedData();
new Producer(sd);
new Consumer(sd);
}
}

Interthread Communication

In this section, you'll learn about the basic methods used to allow threads to communicate with other concurrently running threads.

Methods for Interthread Communication

public final void wait()
Causes this thread to wait until some other thread calls the notify or notifyAll method on this object. May throw InterruptedException.

public final void notify()
Wakes up a thread that called the wait method on the same object.

public final void notifyAll()
Wakes up all threads that called the wait method on the same object.

Java Tutorial: Interthread Communication

For a clearer understanding of these methods, let us consider the waiter-customer scenario. In a restaurant scenario, the waiter waits until a customer enters the place instead of continually asking people if they want to order or need anything. When a customer comes in, this signifies the customer's interest in ordering food from the restaurant. In a way, the customer by entering the restaurant notifies the waiter that he is need of his service. However, it is not always the case that the customer is immediately ready with his order. It would be annoying if the waiter continually asks the customer if he's ready with his order every once in a while. Instead, the waiter waits until the customer notifies him that he's ready. Once the customer finished giving his orders, it would be annoying for him to continually nag the waiter if he's order is ready. Normally, a customer would wait until the waiter notifies him and serves the food.

Observe that in this scenario, a party that waits only wakes up once the other party notifies him. The same is true for threads.

The Callable Interface

Recall that there are two ways of creating threads. We can either extend the Thread class or implement the Runnable interface. In whichever technique used, we customize its functionality by overriding the run method. The method has the following signature:


Java Tutorial Source Code: The Callable Interface

public void run()

The drawbacks in creating threads this way are:
  1. The run method cannot return a result since it has void as its return type.
  2. Second, the run method requires you to handle checked exceptions within this method since the overriden method does not use any throws clause.
The Callable interface is basically the same as the Runnable interface without its drawbacks. To get the result from a Runnable task, we have to use some external means of getting the result. A common technique of which is to use an instance variable for storing the result. The next code shows how this can be done.

public MyRunnable implements Runnable {
private int result = 0;

public void run() {
...
result = someValue;
}

/* The result attribute is protected from changes from other
codes accessing this class */
public int getResult() {
return result;
}
}

Java Tutorial Source Code: The Callable Interface

With the Callable interface, getting the result is simple as shown in the next example.

import java.util.concurrent.*;

public class MyCallable implements Callable {
public Integer call() throws java.io.IOException {
...
return someValue;
}
}

The call method has the following signature:

V call throws Exception

V here is a generic type, which means that the return type of call can be of any reference type. You will learn more about generic types in a latter chapter.

There are still more concurrency features in J2SE5.0. Please refer to the API documentation for a detailed discussion of these other features.