I’m working on the task of monitoring the execution of query, it became necessary to check the query after a certain time. Please, help me, how to implement the method poll correctly? Is it possible to do this in a separate thread? For example, I want to log every iteration of the loop and end the stream on the number 8. how to implement it correctly? Thanks!
public class MyTimerTask implements Runnable {
String name;
private boolean isActive;
void disable(){
isActive=false;
}
MyTimerTask(String name){
isActive = true;
this.name = name;
run();
}
#Override
public void run() {
System.out.println(name + " Start at :" + new Date());
try {
completeTask();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " Finish at:" + new Date());
}
private void completeTask() throws InterruptedException {
for(int i = 0; i<10;i++){
System.out.println(i);
Thread.sleep(1000);
}
}
public static void main(String args[]){
new MyTimerTask("device");
}
}
Try something like this:
public class MyTimerTask implements Runnable {
#Override
public void run() {
System.out.println(name + " Start at :" + new Date());
completeTask();
System.out.println(name + " Finish at:" + new Date());
}
private void completeTask() throws InterruptedException {
for(int i = 0; i<10;i++){
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
new Thread(new MyTimerTask(), "device").start();
}
}
Do not need those fields, java.lang.Thread have those.
Do not call methods from the constructor that requires the instance to be fully created. EG: do not call run() from it.
InterruptedExceptions should be caught, but in this case you may want to swallow it, as it is not signalling an unfinished job...
To create a new thread use the Thread: You can specify the Runnable instance and/or name as arguments of the constructor. Or you can extend it and call super() with the name in the constructor, and implement run() in it.
.
public class MyTimerTask extends Thread {
public MyTimerTask() {
super("device");
}
#Override
public void run() {
System.out.println(name + " Start at :" + new Date());
completeTask();
System.out.println(name + " Finish at:" + new Date());
}
private void completeTask() throws InterruptedException {
for(int i = 0; i<10;i++){
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
new Thread().start();
}
}
You implementation works fine.
You just need include on main method:
public static void main(String args[]){
new Thread(new MyTimerTask("device")).start();
}
Have in mind that according this implementation you'll run the function only 10 times.
As you have a status flag maybe you can use it changing the loop intructoin.
while (isActive) {
System.out.println(name + " Start at :" + Instant.now());
Related
myCode is following:
I want to know why zhangsan and lisi are both can print :
李四9锁对象:1522503870
张三9锁对象:1522503870
public class TicketConsumer implements Runnable {
private Integer i;
public TicketConsumer(int i) {
super();
this.i = i;
}
#Override
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName() + i + "锁对象before:" + System.identityHashCode(i));
synchronized (i) {
System.out.println(Thread.currentThread().getName() + i + "锁对象:" + System.identityHashCode(i));
if (i > 0) {
try {
Thread.sleep(100); // 模拟抢票延迟
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "抢到了第" + i-- + "张票");
} else {
return;
}
}
}
}
public static void main(String[] args) {
TicketConsumer ticket = new TicketConsumer(new Integer(10));
Thread t1 = new Thread(ticket, "张三");
Thread t2 = new Thread(ticket, "李四");
t1.start();
t2.start();
}
}
the result is :
张三10锁对象before:1417180225
李四10锁对象before:1417180225
张三10锁对象:1417180225
张三抢到了第10张票
张三9锁对象before:1522503870
李四9锁对象:1522503870
张三9锁对象:1522503870
李四抢到了第9张票
李四8锁对象before:2045992545
李四8锁对象:2045992545
张三抢到了第9张票
I want to know why 张三 and 李四 both can get:
李四9锁对象:1522503870
张三9锁对象:1522503870
I might be wrong, but when you do i--, you can see that System.identityHashCode(i) changes, so another thread that was waiting outside the synchronized block can now enter it. Synchronizing on objects that change identity/reference is not a good idea, try synchronizing on a Stack and debug with stack.push(...): that will not change reference.
This question already has answers here:
How to use wait and notify in Java without IllegalMonitorStateException?
(12 answers)
Closed 5 years ago.
I am learning multi threading and I am trying to understand how to use wait and notify methods of Object class. I have gone through this link https://www.journaldev.com/1037/java-thread-wait-notify-and-notifyall-example and have written the following program
Waiter
public class Waiter implements Runnable {
private Message m;
public Waiter(Message m) {
this.m = m;
}
public void run() {
String name = Thread.currentThread().getName();
System.out.println(t1 + " thread waiting for message");
synchronized (m) {
try {
m.wait();
System.out.println(t1 + " " + m.getText());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(t1 + " thread waiting for message");
}
}
Notifier
public class Notifier implements Runnable {
private Message m;
public Notifier(Message m) {
this.m = m;
}
public void run() {
synchronized (m) {
try {
Thread.sleep(2000);
m.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Test
public class WaitNotifyTest {
public static void main(String[] str) {
Message m = new Message("hello");
new Thread(new Waiter(m), "t1").start();
new Thread(new Waiter(m), "t2").start();
new Thread(new Notifier(m)).start();
}
}
When I execute the program, it sometimes terminates properly, sometimes it waits indefinitely, sometimes one of the thread terminates and the other waits indefinitely. Can anyone please tell me what is wrong here?
Also I want to know few examples of real time applications of wait and notify methods.
when you are doing wait best practice is do in a while loop with a condition.There can be scenario where thread will notify and after that other thread enter wait state.So thread will go always in wait state
Modified code:
public class Waiter implements Runnable {
private Message m;
public Waiter(Message m) {
this.m = m;
}
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + " thread waiting for message");
synchronized (m) {
try {
while (m.getText() == null) {
m.wait();
}
System.out.println(name + " " + m.getText());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + " thread waiting for message");
}
}
public class Notifier implements Runnable {
private Message m;
public Notifier(Message m) {
this.m = m;
}
public void run() {
synchronized (m) {
m.setText("hello");
m.notifyAll();
}
}
}
public class WaitNotifyTest {
public static void main(String[] str) {
Message m = new Message();
new Thread(new Waiter(m), "t1").start();
new Thread(new Waiter(m), "t2").start();
new Thread(new Notifier(m)).start();
}
}
I am trying to create a program that will carry on running automatically without me having to do anything. I am a bit confused on how to implement runnable in java so I can create a thread that will go to sleep for a certain period of time and then run the re-run the program after the sleep period is over.
public class work {
public static void main(String[] args) throws IOException, InterruptedException {
work test = new work();
test.information();
}
private ConfigurationBuilder OAuthBuilder() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("dy1Vcv3iGYTqFif6m4oYpGBhq");
cb.setOAuthConsumerSecret("wKKJ1XOPZbxX0hywDycDcZf40qxfHvkDXYdINWYXGUH04qU0ha");
cb.setOAuthAccessToken("4850486261-49Eqv5mogjooJr8lm86hB20QRUpxeHq5iIzBLks");
cb.setOAuthAccessTokenSecret("QLeIKTTxJOwpSX4zEasREtGcXcqr0mY8wk5hRZKYrH5pd");
return cb;
}
public void information() throws IOException, InterruptedException {
ConfigurationBuilder cb = OAuthBuilder();
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
try {
User user = twitter.showUser("ec12327");
Query query = new Query("gym fanatic");
query.setCount(100);
query.lang("en");
String rawJSON =null ;
String statusfile = null;
int i=0;
try {
QueryResult result = twitter.search(query);
for(int z = 0;z<5;z++){
for( Status status : result.getTweets()){
System.out.println("#" + status.getUser().getScreenName() + ":" + status.getText());
rawJSON = TwitterObjectFactory.getRawJSON(status);
statusfile = "results" + z +".txt";
storeJSON(rawJSON, statusfile);
i++;
}
}
System.out.println(i);
}
catch(TwitterException e) {
System.out.println("Get timeline: " + e + " Status code: " + e.getStatusCode());
if(e.getErrorCode() == 88){
Thread.sleep(900);
information();
}
}
} catch (TwitterException e) {
if (e.getErrorCode() == 88) {
System.err.println("Rate Limit exceeded!!!!!!");
Thread.sleep(90);
information();
try {
long time = e.getRateLimitStatus().getSecondsUntilReset();
if (time > 0)
Thread.sleep(900000);
information();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
private static void storeJSON(String rawJSON, String fileName) throws IOException {
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(fileName, true);
fileWriter.write(rawJSON);
fileWriter.write("\n");
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
} finally {
if(fileWriter!=null) {
fileWriter.close();
}
}
}
}
You have severable options to implement a thread in Java.
Implementing Runnable
When a class implements the Runnable interface, he has to override the run() method. This runnable can be passed to the constructor of a Thread. This thread can then be executed using the start() method. If you'd like to have this thread run forever and sleep, you could do something like the following:
public class HelloRunnable implements Runnable {
public void run() {
while(true){
Thread.sleep(1000);
System.out.println("Hello from a thread!");
}
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Extending Thread
Thread itself also has a run() method. When extending thread, you can override the Thread's run() method and provide your own implementation. Then you'd have to instantiate your own custom thread, and start it in the same way. Again, like the previous you could do this:
public class HelloThread extends Thread {
public void run() {
while(true){
Thread.sleep(1000);
System.out.println("Hello from a thread!");
}
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
Source: Oracle documentation
Building on the previous answer, you need to either extend Thread or implement Runnable on your Work class. Extending Thread is probably easier.
public class work extends Thread {
public void run() {
// your app will run forever, consider a break mechanism
while(true) {
// sleep for a while, otherwise you'll max your CPU
Thread.sleep( 1000 );
this.information();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
work test = new work();
test.start();
}
// ... rest of your class
}
public static void main(String[] args){
Thread thread = new Thread(runnable); // create new thread instance
thread.start(); // start thread
}
public static Runnable runnable = new Runnable(){
#Override
public void run(){
final int DELAY = 500;
while(true){
try{
// Code goes here;
Thread.sleep(DELAY)
} catch(Exception e){
e.printStackTrace();
}
}
}
}
I'm trying to make a program run two threads through a semaphore. The semaphore must be started to 0.
At the end should display a message on screen:
System.out.println ("string number" + i);
where 'i' is the number of the process
My code is:
public class Orden extends Thread {
int id;
int num;
static Semaphore semaphore = new Semaphore (0);
public Orden(int id)
{
this.id= id;
}
#Override
public synchronized void run()
{
try
{
if(semaphore.availablePermits() == 0){
semaphore.release(1);
System.out.println(semaphore.availablePermits());
}
else{
System.out.println("Thread: " + this.id);
}
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
public static void main(String[] args)
{
Orden o1 = new Orden(1);
Orden o2 = new Orden(2);
o1.start();
o2.start();
}
}
Where am I wrong? What am I doing wrong?
Thanks
Your run is synchronized but you are synchronized on two different objects o1 and o2 so it is effectively not synchronized. You could use a synchronized block on a static object such as semaphore so they would both be synchronized on the same object.
#Override
public void run() {
try {
synchronized (semaphore) {
if (semaphore.availablePermits() == 0) {
semaphore.release(1);
System.out.println(semaphore.availablePermits());
} else {
System.out.println("Thread: " + this.id);
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
I am having a run method which tries to override another run method. But its not happening because I am getting a "Class not found Exception" before it passed on to run method.
Here´s my class with run method
How could I get this over ride the run method.
the class which I have to call in order to execute.
public abstract class MessageProcessor implements Runnable {
private Collection<KpiMessage> fetchedMessages;
private Connection dbConnection;
Statement st = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
private Collection<KpiMessage> outgoingQueue;
public KpiMsg804 MessageProcessor(Collection<KpiMessage> outgoingQueue, Connection
dbConnection){
this.outgoingQueue = outgoingQueue;
this.dbConnection = dbConnection;
return (KpiMsg804) fetchedMessages;
}
public Collection<KamMessage> generate(Collection<KamMessage> outgoingQueue)
{
while(true){
try {
while (rs.next()) {
KamMessage filedClass = convertRecordsetToPojo(rs);
outgoingQueue.add(filedClass);
}
for (KamMessage pojoClass : outgoingQueue) {
KamMsg804 updatedValue = createKamMsg804(pojoClass);
System.out.print(" " + pojoClass.getSequence());
System.out.print(" " + pojoClass.getTableName());
System.out.print(" " + pojoClass.getAction());
System.out.print(" " + updatedValue.getKeyInfo1());
System.out.print(" " + updatedValue.getKeyInfo2());
System.out.println(" " + pojoClass.getEntryTime());
}
return outgoingQueue;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
In your code you are creating a default-visibility field inside a class, and not overriding the run() method. Just stick to:
MessageProcessor processor = new MessageProcessor() {
#Override
final public void run() {
MessageProcessor(outgoingQueue).generate(outgoingQueue);
}
};
And remove the outer MessageProcessor declaration.
I made a subset of your code:
public class PollingSynchronizer {
public static void main(String[] args) {
MessageProcessor message = new MessageProcessor() {
MessageProcessor message = new MessageProcessor() {
public void run() {
System.out.println("new run");
}
};
};
new Thread(message).start();
}
}
class MessageProcessor implements Runnable {
public void run() { System.out.println("old run"); }
}
Which will print old run because the first MessageProcessor::run() it is not really being overwritten.