Created
August 14, 2010 14:35
-
-
Save asim/524354 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("[email protected]")); | |
message.setRecipients(Message.RecipientType.TO, "[email protected]"); | |
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