how to determine the time when you end a sentence during registration? - java

I wrote on my own a set of code to record what I say through a microphone.
I would like to understand the function that google uses for stopping this recording when there is "silence". For example if I go on google and press the microphone symbol, I can say what I plan to look for, but what is the function that it uses to understand the moment when I do not say anything (the moment of "silence")? I thought about doing a cycle in which they are recording some dB or RMS of a few sound frames, and by comparison I can understand if there's "silence".
until now the time is static.
public static void main(String[] args) {
final Main REGISTRAZIONE = new Main();
Thread TIME = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(RECORD_TIME);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
REGISTRAZIONE.finish();
}
});
TIME.start();
REGISTRAZIONE.start();
}

Your approach of checking for dB is good. Then, you can use another Thread to check for silence, and stop the main thread when it finds it. You have to use your own implementation of Thread so that it can take TIME as parameter and stop it when there is silence:
public class Recorder {
static Long RECORD_TIME = 100000L; //or whatever time you use
public static void main(String[] args) {
final Main REGISTRAZIONE = new Main();
Thread TIME = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(RECORD_TIME);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
REGISTRAZIONE.finish();
}
});
TIME.start();
myThread finisher = new myThread(TIME);
finisher.start();
REGISTRAZIONE.start();
}
}
class myThread extends Thread implements Runnable {
private Thread TIME;
public myThread(Thread TIME) {
this.TIME = TIME;
}
public void run() {
while (!silence()) {
// do nothing
}
TIME.interrupt();
}
private boolean silence() {
//record and calculate the dB volume and compare to some level
return true;
}
}

Related

Access synchronized method from another thread using same instance

I've a core method in my project which I need it to be synchronized in order not to be accessed twice at the same time, and hence I have a thread which uses an instance from this class to access this method, but inside this thread I need to have a long life loop to be used to access the same method with a fixed value so I have to use another thread in order to allow the first thread to move on and complete it's duties, but for sure the method doesn't run from that second thread using the same instance used in the first thread, and somehow I can't instantiate another instance from the class as I have to use this instance exactly, so how to overcome this problem.
below is the problem translated to java:
public class ClassOne {
synchronized public void my_method(int number) {
// Do some Work
}
}
public class ClassTwo {
private void some_method() {
Thread one = new Thread(new Runnable() {
#Override
public void run() {
ClassOne class_one = new ClassOne();
// DO Work
class_one.my_method(0);
run_loop(class_one);
// Complete Work
}
});
one.start();
}
boolean running = true;
private void run_loop(final ClassOne class_one) {
Thread two = new Thread(new Runnable() {
#Override
public void run() {
while (running) {
class_one.my_method(1); // won't run
Thread.sleep(10000);
}
}
});
two.start();
}
}
Actual problem overview:
my_method --- > is to send UDP packets.
the method has to be synchronized otherwise I'll get the socket is already open exception when trying to use it more than once repeatedly.
at some point, I have to send a KeepAlive message repeatedly each 10 seconds, so, I have to launch a separate thread for that which is thread two in run_loop method.
Putting something that will compile and work. I don't see why you need this function to be synchronized. Check the output for this program...The second thread access this method only when the first thread is done accessing (unless you have missed adding some additional code).
class ClassOne {
int criticalData = 1;
synchronized public void my_method(int number) {
// Do some Work
criticalData *= 31;
System.out.println("Critical data:" + criticalData + "[" + Thread.currentThread().getName() + "]");
}
}
class ClassTwo {
boolean running = true;
public void some_method() {
Thread one = new Thread(new Runnable() {
public void run() {
ClassOne class_one = new ClassOne();
// DO Work
class_one.my_method(0);
run_loop(class_one);
// Complete Work
}
});
one.start();
}
public void run_loop(final ClassOne class_one) {
Thread two = new Thread(new Runnable() {
public void run() {
while (running) {
class_one.my_method(1); // won't run
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
two.start();
}
}
public class StackExchangeProblem {
public static void main(String[] args) {
ClassTwo two = new ClassTwo();
two.some_method();
}
}

Pass integer to thread

I am (very) very new to Java. The code in question is spawning a thread that performs some action at a specific time. This time is obtained from the main thread that receives it via http://ip:80/time=(int,sec)
Users can call this URL and update this time as many times as they want. This means I have to pass my integer to the thread so that it can run using a given time, such as when it changes. How do I do that?
Here's how my thread is defined and launched:
Thread launchLoadBalancer = new Thread() {
public void run() {
TimerTask timerTask = new TimerTask(serverSocket, //object for extra data);
try {
timerTask.start();
} catch (IOException e) {
}
}
};
launchtimerTask.start();
I have to pass integer from the new TimerTask. I can modify the constructor on the other end. How do I correctly pass integer?
Make a new class that extends Thread and has a constructor that takes an int.
class LaunchLoadBalancerThread extends Thread {
private int i;
public LaunchLoadBalancerThread(int i) {
this.i = i;
}
public void run() {
TimerTask timerTask = new TimerTask(serverSocket, //object for extra data);
try {
timerTask.start();
} catch (IOException e) {
}
}
}
Then, you can use that class (replace i with your number):
Thread launchLoadBalancer = new LaunchLoadBalancerThread(i);
launchLoadBalancer.start();
public class Main {
public static void main(String[] args) {
int length = 1000;
Thread launchLoadBalancer = () -> {
TimerTask timerTask = new TimerTask(serverSocket, length);
try {
timerTask.start();
} catch (IOException e) {
}
};
launchLoadBalancer.start();
}
}

Trying to stop thread, but it start again

Hi I'm using the next code to try to stop a thread, but when I see that Running is false it becomes true again.
public class usoos {
public static void main(String[] args) throws Exception {
start();
Thread.sleep(10000);
end();
}
public static SimpleThreads start(){
SimpleThreads id = new SimpleThreads();
id.start();
System.out.println("started.");
return id;
}
public static void end(){
System.out.println("finished.");
start().shutdown();
}
}
And the thread
public class SimpleThreads extends Thread {
volatile boolean running = true;
public SimpleThreads () {
}
public void run() {
while (running){
System.out.println("Running = " + running);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Shutting down thread" + "======Running = " + running);
}
public void shutdown(){
running = false;
System.out.println("End" );
}
}
The problem is that when I try to stop it(I set running to false), it starts again..
Look at this line in the end method:
start().shutdown();
You are not stopping the original instance; you are starting another one, which you then immediately shut down.
There is no connection between your start and end methods—no information, no reference is passed from one to the other. It is obviously impossible to stop the thread you started in the start method.
Your end method should not be static; in fact, you don't even need it, shutdown is already it:
SimpleThreads t = start();
Thread.sleep(10000);
t.shutdown();
Because in the end method you just create a new Thread and kill it, save the thread instance and kill it:
Your code should look something like this:
public class usoos {
public static void main(String[] args) throws Exception {
SimpleThreads id = start();
Thread.sleep(10000);
end(id);
}
public static SimpleThreads start(){
SimpleThreads id = new SimpleThreads();
id.start();
System.out.println("started.");
return id;
}
public static void end(SimpleThreads id){
System.out.println("finished.");
id.shutdown();
}

How can I start, pause and resume my threads? (by extending thread from classes)

Essentially, what I want to do is start all my threads, pause them all, then resume them all, using the multithreading approach. I am just looking for a simple solution to this. I'm not sure if I have to use a timer or what. Right now when I run it, the threads are like being executed in random order (I guess the PC is just randomly picking which ones it wants to run at a certain time).
class ChoppingThread extends Thread
{
public void run()
{
for(int j=40;j!=0;j-=10)
System.out.println("Chopping vegetables...("+j+" seconds left)");
}
}
class MixingThread extends Thread
{
public void run()
{
for(int k=60;k!=0;k-=10)
System.out.println("Mixing sauces...("+k+" seconds left)");
}
}
class TenderizingThread extends Thread
{
public void run()
{
for(int j=50;j!=0;j-=10)
System.out.println("Tenderizing meat...("+j+" seconds left)");
}
}
class MultiThreadTasking
{
public static void main (String [] args)
{
ChoppingThread ct = new ChoppingThread();
MixingThread mt = new MixingThread();
TenderizingThread tt = new TenderizingThread();
System.out.println("\nWelcome to the busy kitchen.");
//putting threads into ready state
ct.start();
mt.start();
tt.start();
}
}
There are probably other ways to achieve the same result, but this is the simplest I can come up with off the top of my head (I know, sad isn't it)...
Basically, this is a special Runnable with some additional management functionality.
This basically contains a state flag that indicates the state of the task and a monitor lock
public class ThreadFun {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
task.pauseTask();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
task.resumeTask();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
task.stopTask();
}
public enum TaskState {
Running,
Stopped,
Paused
}
public static class MyTask implements Runnable {
private static final Object PAUSED_LOCK = new Object();
private volatile TaskState state = TaskState.Running;
public void pauseTask() {
if (state == TaskState.Running) {
System.out.println("Paused...");
state = TaskState.Paused;
}
}
public void resumeTask() {
if (state == TaskState.Paused) {
state = TaskState.Running;
synchronized (PAUSED_LOCK) {
PAUSED_LOCK.notifyAll();
}
System.out.println("Resumed...");
}
}
public void stopTask() {
if (state == TaskState.Running || state == TaskState.Paused) {
state = TaskState.Stopped;
System.out.println("Stopped...");
}
}
public boolean isStopped() {
return state == TaskState.Stopped;
}
public boolean isPaused() {
return state == TaskState.Paused;
}
protected void doPause() {
synchronized (PAUSED_LOCK) {
while (isPaused()) {
try {
PAUSED_LOCK.wait();
} catch (InterruptedException ex) {
}
}
}
}
#Override
public void run() {
int index = 0;
while (!isStopped() && index < 1000) {
try {
Thread.sleep(25);
} catch (InterruptedException ex) {
}
doPause();
index++;
System.out.println(index);
}
stopTask(); // Make sure the task is marked as begin stopped ;)
}
}
}
The main criteria is you will need to pool isStopped and doPause at appropriate points to ensure that they are begin implemented as required...
To coordinate them use a CyclicBarrier.
To launch them all at the same time use a CountDownLatch.
Google the two classes above for many examples and explanations.
To fully understand what is happening read the Java Concurrency In Practice book.
I believe you can accomplish this by using Object.wait and Thread.interrupt.
Object.wait blocks until notify is called. So
private boolean paused;
private Object waitObject;
...
public void run() {
for ... {
if (this.paused) { this.waitObject.wait(); }
...
public void pause() { this.paused = true; }
public void resume() { this.paused = false; this.waitObject.notify(); }
Then you can call pause to pause the thread.
Thread.interrupt can help with stopping.
private boolean paused;
...
public void run() {
for ... {
// interrupted() is different from interrupt()!
if (this.iterrupted()) { break; }
...
To stop it, you would call interrupt() from another thread.
This is the basic idea, but there's a lot of details to worry about here. For example, wait can throw an InterruptedException you'll need to handle. Also, wait is not guaranteed to return only after a notify. It can return randomly. Here is a pair of tutorials:
Wait: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
Interrupt: http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

Thread synchronization/producer-consumer in java. Printing out numbers 1-10 then 10-1 repeatedly

I'm very new to java and found an exercise to work on basic thread synchronization. The problem is to print out 12345678910 10987654321 repeatedly until the program stops. Ten different threads should be used.
This is my code so far:
I am first working on trying to get just the first number (number one to work), but it keeps giving me an exception
public static void main(String[] args){
threadOne one = new threadOne();
one.start();
}
}
class updateNumber{
private int i;
synchronized void increase(int s){
this.i=s;
System.out.println(i);
}
}
class threadOne extends Thread {
private updateNumber grab;
public void run() {
try{
grab.increase(1);
}
catch(Exception e){
System.out.println("error in thread one");
}
}
}
I may be going about this the completely wrong way, but I've read a lot of documentation and am just thoroughly confused.
It looks like you didnt create a new instance of update
class threadOne extends Thread {
private updateNumber grab;
public void run() {
try{
grab.increase(1); // null pointer reference...<<<<<<<
}
catch(Exception e){
System.out.println("error in thread one");
}
}
}
// you need to alocate memory to updateNumber like this
//private updateNumber grab = new updateNumber();
class threadOne extends Thread {
private updateNumber grab = new updateNumber();
public void run() {
try{
grab.increase(1);
}
catch(Exception e){
System.out.println("error in thread one");
}
}
}

Categories