I have two options to execute my program (I need to have Out_str as a result).
Option 1:
Out_str = "";
for (i = 1; i <= 20000; i++) {
Out_str = Out_str + "word";
}
Option2:
Runnable runnable1 = new Runnable() {
public void run() {
Out_str1 = "";
for (i1 = 1; i1 <= 10000; i1++) {
Out_str1 = Out_str1 + "word";
}
}
};
Runnable runnable2 = new Runnable() {
public void run() {
Out_str2 = "";
for (i2 = 1; i2 <= 10000; i2++) {
Out_str2 = Out_str2 + "word";
}
}
};
Thread thread1 = new Thread(runnable1);
thread1.start();
Thread thread2 = new Thread(runnable2);
thread2.start();
Why using threads does not make my program execute faster (in both cases the execution takes approx 12 sec with my laptop)? What shall I use in this case (to make it faster to obtain Out_str)? Will using services make help in this case?
The Thread allows you to run processes concurrently. You haven't gained any processing power though, with equal priority your threads would be run in a round-robin way I would guess.
Related
I'm working on a school project in Android Studio and so far I've written a code which generates a random equation and then display this equation in a textview. Here is the code:
String[] operationSet = new String[]{"+", "-", "/", "*"};
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation = "";
for (int i = 0; i < numOfOperations; i++) {
equation += numbers.get(i);
equation += operations.get(i);
}
equation += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView3);
TextEquation.setText(equation);
String stringResultOfEquation = String.valueOf(equation);
// Resultat der Rechung berechnen
double doubleAnswer = eval(stringResultOfEquation);
String stringAnswer = Double.toString(doubleAnswer);
TextView textAnswer = (TextView)findViewById(R.id.textView4);
textAnswer.setText(stringAnswer);
So far I've tried to use the TimerTask command:
TimerTask timerTaskWaiting = new TimerTask() {
#Override
public void run() {
}
};
Timer timerwaiting = new Timer();
timerwaiting.schedule(timerTaskWaiting, 5000);
I've put the "equation generater code" and put it into "public void run(){...}" but the app crashed when I tried it out.
My question now is, if there is a simple way which will generate the equation after a certain amount of time (for example 5 seconds) I mean, I want that the equation will be generated 5 seconds after the app is launched.
If there is anything unclear in my question, feel free to ask and I will try to clarify the problem :)
Thank you already in advance for your help!
This bit of code should suffice for you to understand what you need to do. obviously there are other ways you can achieve this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
generateAndDisplayEquation();
}
}, 5000);
}
Use RxJava library, it is very easy tool to organize periodic tasks.
I searched other posts and I didn't find a case matching my problem, so please do not refer me to other posts.
I have a list of hundreds of different times starting like the below list:
timeList = {5, 13, 21, 40, ...}.
Suppose that they are saved in an arraylist. That means some task must be executed at 5 secs, 13 secs,... from a starting point . How can I use a Timer or any other way to achieve this?
Also I may have the timeList in a format like this if it helps:
timeList = {8:05, 8:13, 8:21, 8:40, ...}.
My current timer is like this:
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
//do some task
}
}, startPoint, Period);
But this is obviously working at fixed rate!
By using Timer.schedule(TimerTask task, long delay), set all your timers and wait for them to execute
Assuming you are getting in MM:SS format (ex: 8:58):
ArrayList<String> your_arraylist = new ArrayList<String>();
//your list above, fill it with MM:SS
final ArrayList<Long> seconds = new ArrayList<Long>();
final ArrayList<Long> minutes = new ArrayList<Long>();
long first_minute;
for (String time : your_arraylist) {
minutes.add(Long.parseLong(time.split(":")[0]));
seconds.add(Long.parseLong(time.split(":")[1]));
}
first_minute = minutes.get(0);
for (int i = 0; i < seconds.size(); i++) {
long waiting_duration;
if (seconds.get(i) < Calendar.SECOND) {
waiting_duration = (60 - Calendar.SECOND + seconds.get(i)) * 1000;
}
else {
waiting_duration = (seconds.get(i) - Calendar.SECOND) * 1000;
}
waiting_duration += (minutes.get(i) - first_minute) * 60 * 1000;
Timer timer = new Timer();
TimerTask timer_task = new TimerTask() {
#Override
public void run() {
// do jobs
}
};
timer.schedule(timer_task, waiting_duration);
}
Don't use Timer use a Handler instead.
private int[] mTimeList = {5000, 2000, 7000, 4000};
private int mCount;
private int mDelay;
private Handler mHandler = new Handler();
private void initRepeatedTimer() {
mHandler.postDelayed(new Runnable() {
public void run() {
Log.e(TAG, "run: " + mCount);
mDelay = mTimeList[mCount];
if (mCount < mTimeList.length - 1)
mCount++;
else
mCount = 0;
mHandler.postDelayed(this, mDelay);
}
}, mDelay);
}
You wil notice that the log is printed as per delay in the list.
I want slider in my imageview but it gives me only one image at a time if any one of you have a solution please tell me.
here in my activity class.
images come from the API and there is a whole path of every image and its a web url
ArrayList<String> imagepath1 = i.getExtras().getStringArrayList("event_photo");
for (int i1 = 0; i1 < imagepath1.size(); i1++) {
stockArr = new String[imagepath1.size()];
stockArr = imagepath1.toArray(stockArr);
// imagepath = stockArr.toString();
String imagepath = stockArr[i1];
}
if (!TextUtils.isEmpty(imagepath)) {
if (imagepath.endsWith(".jpeg") || imagepath.endsWith(".jpg")
|| imagepath.endsWith(".gif") || imagepath.endsWith(".png")) {
imageLoader = new ImageLoader(mcontext);
mUpdateResults = new Runnable() {
public void run() {
Animation rotateimage = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.alpha);
for (int i2 = 0; i2 < stockArr.length; i2++) {
imageLoader.DisplayImage(imagepath1.get(i2),
imagetop);
// imagetop.startAnimation(rotateimage);
/*imagetop.setImageResource(number[currentimageindex
% stockArr.length]);*/
}
}
};
final Handler mHandler = new Handler();
int delay = 500; // delay for 1 sec.
int period = 5000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
} else {
}
}
Please Help if any one have a solution
I'm trying to append letters from a specific string onto a TextField. This is what I've tried so far. But no luck.
What happens here is it just waits for 100 milliseconds and then displays the string directly.
outConsole = (TextView) findViewById(R.id.outconsole);
int i, j;
String fin = "";
final String in = "HELLO!";
i = in.length;
try{
for(j = 0; j < i; j++){
Thread.sleep(100);
fin = fin + in.charAt(j);
outConsole.setText(fin);
}
}catch(Exception e){}
}
How do I achieve this?
I would like something like this but slower:
https://www.youtube.com/watch?v=Ff-eDOGLuYw
Try using Handlers. Something like this should work:
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
//update your ui
handler.postDelayed(this, 100);//this restarts the handler better to have some terminating condition
}
};
handler.postDelayed(runnable, 100);//starts the handler first time
Since AnimationDrawable's memory blows up after a few images, I needed to write my own. Google has some demonstrations regarding efficient frame animations, but it is very complicated(needlessly?).
Here is my initial approach, can I get some experts/smart ppl to chime in?
Create a Handler on the UI Thread.
create runables (A) for the handler.
inside the runables (A), I create AsyncTasks for each frame.
each AsyncTask is run using PostDelay to achieve desired frame rate.
the target ImageVew is set wigh the new frame from the AsyncTask.
Here is the code:
private void addTask(Handler handler, final String animationName, final int frameNumber, final AsyncTaskLoadBitmap asyncLoadBitmap, int frameIndex) {
Runnable runnable = new Runnable() {
#Override
public void run() {
int frameIdentifier = getResources().getIdentifier(animationName, "drawable", getPackageName());
Log.v("Runable","adding name");
new AsyncTaskLoadBitmap(imageView,thisActivity).execute(frameIdentifier);
}
};
boolean done = handler.postDelayed(runnable,100 + (100 * frameIndex));
Log.v("PostDelayed","Done");
}
The problem I'm having is making it loop and a way to stopping the loop.
What could be a better approach?
try this:
final ImageView iv = new ImageView(this);
setContentView(iv);
final int LOAD = 1;
final int SHOW = 2;
HandlerThread loader = new HandlerThread("frameLoader");
loader.start();
Callback callback = new Callback() {
int idx = 0;
int[] ids = {
R.drawable.ic_launcher, R.drawable.layer0, R.drawable.layer1,
};
Resources res = getResources();
#Override
public boolean handleMessage(Message msg) {
if (msg.what == LOAD) {
Log.d(TAG, "handleMessage LOAD " + Thread.currentThread().getName());
idx++;
if (idx < 18) {
Bitmap btm = BitmapFactory.decodeResource(res, ids[idx % ids.length]);
msg = mUIHandler.obtainMessage(SHOW, btm);
mUIHandler.sendMessage(msg);
}
} else
if (msg.what == SHOW) {
Log.d(TAG, "handleMessage SHOW " + Thread.currentThread().getName());
iv.setImageBitmap((Bitmap) msg.obj);
mBackgroundHandler.sendEmptyMessageDelayed(LOAD, 500);
}
return true;
}
};
mBackgroundHandler = new Handler(loader.getLooper(), callback);
mUIHandler = new Handler(callback);
mBackgroundHandler.sendEmptyMessage(LOAD);