quinta-feira, 1 de dezembro de 2011

The SimpleThreads Example

The SimpleThreads Example

The following example brings together some of the concepts of this section. SimpleThreads consists of two threads. The first is the main thread that every Java application has. The main thread creates a new thread from the Runnable object, MessageLoop, and waits for it to finish. If the MessageLoop thread takes too long to finish, the main thread interrupts it. The MessageLoop thread prints out a series of messages. If interrupted before it has printed all its messages, the MessageLoop thread prints a message and exits.
public class SimpleThreads {

    //Display a message, preceded by the name of the current thread
    static void threadMessage(String message) {
        String threadName = Thread.currentThread().getName();
        System.out.format("%s: %s%n", threadName, message);
    }

    private static class MessageLoop implements Runnable {
        public void run() {
            String importantInfo[] = {
                "Mares eat oats",
                "Does eat oats",
                "Little lambs eat ivy",
                "A kid will eat ivy too"
            };
            try {
                for (int i = 0; i < importantInfo.length; i++) {
                    //Pause for 4 seconds
                    Thread.sleep(4000);
                    //Print a message
                    threadMessage(importantInfo[i]);
                }
            } catch (InterruptedException e) {
                threadMessage("I wasn't done!");
            }
        }
    }

    public static void main(String args[]) throws InterruptedException {


        //Delay, in milliseconds before we interrupt MessageLoop
        //thread (default one hour).
        long patience = 1000 * 60 * 60;

        //If command line argument present, gives patience in seconds.
        if (args.length > 0) {
            try {
                patience = Long.parseLong(args[0]) * 1000;
            } catch (NumberFormatException e) {
                System.err.println("Argument must be an integer.");
                System.exit(1);
            }

        }

        threadMessage("Starting MessageLoop thread");
        long startTime = System.currentTimeMillis();
        Thread t = new Thread(new MessageLoop());
        t.start();

        threadMessage("Waiting for MessageLoop thread to finish");
        //loop until MessageLoop thread exits
        while (t.isAlive()) {
            threadMessage("Still waiting...");
            //Wait maximum of 1 second for MessageLoop thread to
            //finish.
            t.join(1000);
            if (((System.currentTimeMillis() - startTime) > patience) &&
                    t.isAlive()) {
                threadMessage("Tired of waiting!");
                t.interrupt();
                //Shouldn't be long now -- wait indefinitely
                t.join();
            }

        }
        threadMessage("Finally!");
    }
}

terça-feira, 22 de novembro de 2011

Defining and Starting a Thread

 An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:
Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:

public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }

}
Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:

public class HelloThread extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }

}
 Notice that both examples invoke Thread.start in order to start the new thread.

 Which of these idioms should you use? The first idiom, which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread. The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. This lesson focuses on the first approach, which separates the Runnable task from the Thread object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.

 The Thread class defines a number of methods useful for thread management. These include static methods, which provide information about, or affect the status of, the thread invoking the method. The other methods are invoked from other threads involved in managing the thread and Thread object. We'll examine some of these methods in the following sections.

sexta-feira, 26 de agosto de 2011

CRIANDO UM ARQUIVO .TXT

O próximo programa cria um arquivo .txt usando o File do pacote io ( entrada e saída ):


import java.io.*;

public class Programa1 {
public static void main(String[] args) throws IOException{
File f=new File("roberto.txt");
char [] caracteres=new char[10];
try{
Writer fw=new BufferedWriter(new PrintWriter(new FileWriter(f)));
fw.write("Sersoft");
fw.flush();
fw.close();
System.out.println(f.exists());
System.out.println(f.lastModified());

Reader fr=new FileReader(f);
while(fr.read(caracteres)!=-1)
for(char c:caracteres)
System.out.print(c);
}catch(IOException e){
System.out.println("Não foi possível criar o arquivo");
}

}
}

SEPARADOR DE LETRAS


Para começar gostaria de postar um programa simples para separar letras de números numa variável:


package MEUSTESTES;

public class SeparadorDeLetras {
public static void main(String[] args) {
        String teste = "M1e2t3a4l5u6r7g8i9c0a1R2o3c4h5a";
        char [] caracter = teste.toCharArray();
        String LETRAS ="";
        String NUMEROS ="";
        System.out.println((int)'a');
        for (char c : caracter ) {
            if(Character.isDigit(c)){
                NUMEROS += c;
            }
            else{
                LETRAS += c;
            }
        }
         
        System.out.println("Numeros: "+NUMEROS);
        System.out.println("Letras: "+LETRAS);
    }
 
}