Skip to content

Instantly share code, notes, and snippets.

@asim
Created August 14, 2010 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asim/524354 to your computer and use it in GitHub Desktop.
Save asim/524354 to your computer and use it in GitHub Desktop.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
public class ThreadExample {
private static class WorkerThread extends Thread {
javax.mail.internet.MimeMessage message;
public WorkerThread(String body) {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host","127.0.0.1");
properties.setProperty("mail.smtp.port", "2025");
Session session = Session.getDefaultInstance(properties);
message = new MimeMessage(session);
message.setFrom(new InternetAddress("foo@bar.com"));
message.setRecipients(Message.RecipientType.TO, "bar@foo.com");
message.setSubject("Greetings");
message.setText(body);
}
public void run() {
try {
for (int i = 0; i < 1000; i++){
Transport.send(message);
}
} catch (Exception e) {
System.out.println("Failed sending message");
}
}
}
public static void main(String[] args) throws Exception {
File foo = new File("foo1");
String body = getContents(foo);
WorkerThread[] threads = new WorkerThread[100];
for (int i=0; i < 100; i++) {
threads[i] = new WorkerThread(body);
threads[i].start();
}
try {
for (int j=0; j < 100; j++) {
threads[j].join();
}
} catch (InterruptedException e) {
System.out.println("Threading Error");
}
}
public static String getContents(File aFile) {
//...checks on aFile are elided
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment