Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to pause and resume the thread.  RSS feed

 
Vijay kumar p
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my program i am getting email ids from the database (around 20000)and sending a mail. I have used the Runnable interface to run my java class.Now i have requirement to pause the thread for some time and resume it after.If i pause the thread at particular time it should stop sending mail at that point and after i resume it should start from the particular point from where i have paused.Please help me in this.

[ December 17, 2007: Message edited by: Vijay kumar p ]
[ December 17, 2007: Message edited by: Vijay kumar p ]
 
Edward Harned
Ranch Hand
Posts: 291
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read about Thread.sleep()
 
Atulya Mahajan
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could have a flag 'paused' in your thread class. In the run() method, you test this flag everytime before sending out an email, and only send it if the flag is not set. Otherwise sleep for some time.
Whenever you want to 'pause' your thread, you set the flag, and clear it once you are ready to resume.

Does this help?
 
Vijay kumar p
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks i will test this by setting he flag.But if there is two or more thread it will work, at this time how to make the particular thread to pause.
 
Anand Karia
Ranch Hand
Posts: 156
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks i will test this by setting he flag.But if there is two or more thread it will work, at this time how to make the particular thread to pause


For every thread class, for stopping and resuming thread you need flag that cause to make them enable to run and stop according to your need.

Thread.sleep( ); This will make your thread class to stop for a while (in miliseconds) you have given in between Thread.sleep(200)

If you can post your code here then we can easily tell you where you can make/place flag(s).

Hope this can help you out.
 
Vijay kumar p
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class MailBlaster implements Runnable
{
private Thread runner;
private QueryManager qm;
private Connection conn;
private Statement stmt,stmt1;
private ResultSet rs,rs1;
private static boolean terminate=true;
Timestamp startTime, endTime;

public MailBlaster()
{
try
{
qm = QueryManager.getInstance();
conn = qm.getConnection();
stmt = conn.createStatement();

runner = new Thread(this);
runner.setPriority(3);
runner.setDaemon(false);
runner.start();
try
{
runner.getState();
Thread.sleep(3000);
}
catch(InterruptedException ie)
{
LogManager.getInstance().log(LogLevel.ERROR,"Problem While terminating the thead : "+ie.getStackTrace(),MailBlaster.class);
}
System.out.println("terminate: "+terminate);
if(!terminate)
{
//endTime = new Timestamp(new Date(System.currentTimeMillis()).getTime());
qm.closeConnection(conn);
//LogManager.getInstance().log(LogLevel.INFO,"MailBlaster Endded at: "+Utils.formatTimeStamp(endTime, MailBlastConstants.DATE_TIME_FORMAT),MailBlaster.class);
}
}
catch (Exception e)
{
e.printStackTrace();
LogManager.getInstance().log(LogLevel.ERROR,"Error while creating the Connection : "+e.getStackTrace(),MailBlaster.class);
}
}
public void run()
{
try
{
runMailBlaster();
}
catch (Exception e)
{
LogManager.getInstance().log(LogLevel.ERROR,"Error in method runMailBlaster().. "+e,MailBlaster.class);
}
if(terminate)
{
terminate = false;
endTime = new Timestamp(new Date(System.currentTimeMillis()).getTime());
qm.closeConnection(conn);
LogManager.getInstance().log(LogLevel.INFO,"MailBlaster Endded at: "+Utils.formatTimeStamp(endTime, MailBlastConstants.DATE_TIME_FORMAT),MailBlaster.class);

return;
}
}
private void runMailBlaster()
{
synchronized(this)
{
startTime = new Timestamp(new Date(System.currentTimeMillis()).getTime());
LogManager.getInstance().log(LogLevel.INFO,"MailBlaster Started at: "+Utils.formatTimeStamp(startTime, MailBlastConstants.DATE_TIME_FORMAT),MailBlaster.class);
try
{
//do
//{
rs = stmt.executeQuery("select camp_launch, launch_time, camp_id from mail_campaign");
do
{
if(!rs.next())
break;
int camp_launch = rs.getInt("camp_launch");
int camp_id = rs.getInt("camp_id");
Timestamp compareLaunch_time = rs.getTimestamp("launch_time");
if(camp_launch == 1 && !startTime.before(compareLaunch_time))
{
stmt1 = conn.createStatement();
rs1 = stmt1.executeQuery("select * from camp_report where camp_id = '"+camp_id+"'");
if(!rs1.next())
{
rs1.close();
String strHtmlData = "";
rs1 = stmt1.executeQuery("select html_data from mail_campaign where camp_id = '"+camp_id+"'");
if(rs1.next())
strHtmlData = rs1.getString("html_data");
rs1.close();

StringBuffer stringbuffer = new StringBuffer(strHtmlData);
int no_of_links = 0, link_no = 0;
Hashtable<Integer, String> hash = new Hashtable<Integer, String>();
for(int j = 0; strHtmlData.indexOf("href=\"http://", j) != -1; j++)
{
j = strHtmlData.indexOf("href=\"http://", j);
if(j != -1)
{
no_of_links++;
int j1 = strHtmlData.indexOf("\"", j+7);
String htmlData = strHtmlData.substring(j+6, j1);
hash.put((link_no+1),htmlData);
link_no++;
}
}
stmt1.executeUpdate("insert into camp_report (camp_id, mail_sent, mail_opened, no_of_links, mail_unsub) " +
"values ('"+ camp_id+"', 0, 0, '"+ no_of_links +"', 0)");
for(Enumeration e = hash.keys(); e.hasMoreElements()
{
Integer key = (Integer) e.nextElement();
String link_url = (String)hash.get( key );
//String insertQuery = "insert into camp_link (link_no, camp_id, link_url, no_of_visits) " +
//"values ('"+ key.intValue() +"', '"+ camp_id +"', '"+ link_url +"', 0)";
//stmt1.executeUpdate(insertQuery);
}
int j2 = 0;
for(link_no = 0; link_no < no_of_links; link_no++)
{
j2 = stringbuffer.toString().indexOf("href=\"http://", j2);
j2++;
stringbuffer.replace(j2 + 5, j2 + 12, "http://localhost:8080/MailBlasterApplication2.1/report.do?dispatch=updateLinkCount&link_no=" + (link_no+1) + "&camp_id=" + camp_id + "&link=");
j2 += 12;
}

strHtmlData = stringbuffer.toString();

String from_name = "";
String from_email = "";
String mail_subject = "";
String attach_filepath = "";
int unsubs_reqd = 0;
rs1 = stmt1.executeQuery("select html_data, unsubs_reqd, from_name, from_email, mail_subject, attach_filepath from mail_campaign where camp_id='"+camp_id+"'");
if(rs1.next())
{
from_name = rs1.getString("from_name");
from_email = rs1.getString("from_email");
mail_subject = rs1.getString("mail_subject");
unsubs_reqd = rs1.getInt("unsubs_reqd");
attach_filepath = rs1.getString("attach_filepath");
}
rs1.close();

int increment = 0;
String list_ids = "";
StringBuffer listID = new StringBuffer();
String delim = ",";
rs1 = stmt1.executeQuery("select list_id from camp_list where camp_id='"+camp_id+"'");
while(rs1.next())
{
listID.append(rs1.getInt("list_id"));
listID.append(delim);
if ((listID.length() - delim.length()) >= 0)
list_ids = (listID.substring(0, (listID.length() - delim.length()))).toString();
}
rs1.close();

Map<String, String> memberDetail = new TreeMap<String, String>();
rs1 = stmt1.executeQuery("select * from list_member where list_id IN("+ list_ids +") and member_unsub= 0");
while(rs1.next())
{
String member_name = rs1.getString("member_name");
String member_email = rs1.getString("member_email");
memberDetail.put(member_email.trim(),member_name);
}
rs1.close();

Set<Map.Entry<String, String>> treeSet = memberDetail.entrySet();
Iterator<Map.Entry<String, String>> it= treeSet.iterator();
while(it.hasNext())
{
Map.Entry<String,String> itt=(Map.Entry<String,String> it.next();
String name = itt.getValue();
String emailID = itt.getKey();
stringbuffer = new StringBuffer(strHtmlData);

int l = 0, m = 0;
while(l != -1)
{
l = stringbuffer.toString().indexOf("%name%");
if(l != -1)
stringbuffer.replace(l, l + 6, name);
}
while(m != -1)
{
m = stringbuffer.toString().indexOf("%email%");
if(m != -1)
stringbuffer.replace(m, m + 7,emailID);
}
int k3 = stringbuffer.toString().indexOf("</body>");
if(k3 != -1)
stringbuffer = new StringBuffer(stringbuffer.toString().substring(0, k3));

if(unsubs_reqd == 1)
{
rs1 = stmt1.executeQuery("select unsub_content from unsub_detail");
if(rs1.next())
{
stringbuffer.append(rs1.getString("unsub_content"));
}
rs1.close();
}
stringbuffer.append("<table border=0 cellpadding=5 cellspacing=0 width=100%>");
stringbuffer.append("<tr><td><font face='arial,verdana' size=1><br>");
stringbuffer.append("<td align=right><img src='http://localhost:8080/MailBlasterApplication2.1/report.do?dispatch=updateReport&camp_id=" + camp_id + "&email=" + emailID + "' border='0' title=' '></td>");
stringbuffer.append("</tr></table></body></html>");

try
{
SendMail.sendEmail(MailBlastConstants.emailHost, MailBlastConstants.emailPort, MailBlastConstants.userName, MailBlastConstants.password, from_name, from_email, emailID, MailBlastConstants.EMAIL_MESSAGE_MIME_TYPE_HTML_TEXT, mail_subject, stringbuffer.toString(), attach_filepath);
//stmt1.executeUpdate("update camp_report set mail_sent=mail_sent+1 where camp_id='"+camp_id+"'");
//stmt1.executeUpdate("insert into sent_mail_list (camp_id, member_email) values(" + camp_id + ",'" + emailID + "')");
System.out.println(emailID);
increment++;
}
catch(Exception e)
{
e.printStackTrace();
LogManager.getInstance().log(LogLevel.ERROR,"Error in thread : "+e,MailBlaster.class);
}
}
}
}
}while(true);
try
{
Thread.sleep(2000);
}
catch(InterruptedException ie)
{
LogManager.getInstance().log(LogLevel.ERROR,"Error while thread sleep : "+ie.getStackTrace(),MailBlaster.class);
}
//}while(true);
}
catch (Exception e)
{
LogManager.getInstance().log(LogLevel.ERROR,"Error in method runMailBlaster() : "+e.getStackTrace(),MailBlaster.class);
}
}
}
}
[ December 18, 2007: Message edited by: Vijay kumar p ]
 
Vijay kumar p
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
above is my code in this where is should pause the thread(where i should set the flag)
 
Atulya Mahajan
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well Vijay, that is a lot of code, and hard to read
A shorter snippet might have been more helpful
 
Tushar Kapila
Ranch Hand
Posts: 35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



objSync is an Object used to lock declared as

so when setting the bPause use same code


when pasting code use the CODE tag!
[ December 23, 2007: Message edited by: Jim Yingst ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!