I need to write an Application that extends the Thread class. My class accepts an integer(i.e. 100) when it is instantiated. (MyThread myt = new MyThread(100); )
This integer number will be the number of times that this class loops and prints a message. The message should read “The Thread is running… 100”. The 100 would be whatever number I passed into the constructor. If the number was 150, then the output should read “ The Thread is running… 100”. I should use a main method to test this class. In the main I will start 2 Threads, one Thread with 150 and one Thread with 200. I don't need to use the sleep() method for this code.
I already wrote a code, but I'm confused. Should my message be printed 100 times? I'm not sure if my code meets all requisites.
I should also implement this code changing this class to use the Runnable Interface instead of Thread class
public class MyThread extends Thread {
private int numtimes;
public MyThread(int numtimes) {
this.numbtimes = numbtimes;
}
public void run() {
for (int i = 0; i < numbtimes; i++) {
System.out.println("Thread Running..." + numbtimes);
}
}
public static void main(String[] args) {
MyThread mytr1 = new MyThread(150);
mytr1.start();
MyThread mytr2 = new MyThread(200);
mytr2.start();
}
}
Is that what was asked? How would you do using Runnable Interface?
two way you can use. Actually the same kind. but I prefer lambda
public class StackOverFlowDemo {
/**
* one
* */
public static class MyRun implements Runnable {
private int numtimes;
public MyRun(int numtimes) {
this.numtimes = numtimes;
}
#Override
public void run() {
for (int i = 0; i < numtimes; i++) {
System.out.println(String.format("Thread(%s) Running... numtimes(%d), current count (%d) ",
Thread.currentThread().getName(),
numtimes, i));
}
}
}
/**
* another way
* */
public static void print(int numtimes) {
for (int i = 0; i < numtimes; i++) {
System.out.println(String.format("Thread(%s) Running... numtimes(%d), current count (%d) ",
Thread.currentThread().getName(),
numtimes, i));
}
}
public static void main(String[] args) {
/**
* one
* */
Thread t1 = new Thread(new MyRun(150), "thread 1");
Thread t2 = new Thread(new MyRun(200), "thread 2");
t1.start();
t2.start();
/**
* another way
* */
new Thread(() -> StackOverFlowDemo.print(150), "t1").start();
new Thread(() -> StackOverFlowDemo.print(200), "t2").start();
}
}
Related
I am working on a multi-thread program. Can someone please help me on how to implement the sleep method within my program. I have never used it and the requirement is that the run method uses the sleep method. I did start 4 threads and checked the outlined ranges. and I should Modify the Finder class so its run method utilizes the sleep method. I have never used the sleep method.
import static java.lang.System.out;
class Range
{
int start;
int end;
Range(int s, int e)
{
start = s;
end = e;
}
boolean contains(int x)
{
return end - start >=0;
}
}
class Finder implements Runnable
{
#Override
public void run()
{
}
}
public class ThreadTest implements Runnable
{
static void log(Object o){out.print(o);}
static void logLn(Object o){out.println(o);}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* #see Thread#run()
*/
#Override
public void run()
{
logLn("Running main");
}
static Range myRange = new Range(100, 500);
public static void main(String[] args)
{
if (myRange.contains(300))
{
System.out.println ("You\'re within the correct range.");
}
Finder fc = new Finder();
Thread t1= new Thread(fc);
t1.start();
Thread t2= new Thread(fc);
t2.start();
Thread t3 = new Thread(fc);
t3.start();
Thread t4 = new Thread(fc);
t4.start();
Runnable myRunnable = new Runnable(){
public void run(){
System.out.println("Runnable running");
}
};
myRunnable.run();
}
}
Sleep is a static method provided by the Thread class via Thread.sleep(1000L) where the value you pass is a Long representing milliseconds. Implementing a sleep method doesn't make much sense but calling Thread.sleep() will suspend the current thread that is executing that call.
So my guess is that you are supposed to call Thread.sleep within the run function of Finder.
EDIT
Implementing would simply be calling what I explained:
class Finder implements Runnable{
#Override
public void run(){
System.out.println("Thread " + Thread.currentThread().getId() + " sleeping");
Thread.sleep(1500L);
System.out.println("Thread " + Thread.currentThread().getId() + " awake");
}
}
This question already has answers here:
why doesn't this synchronized method work as expected?
(3 answers)
Closed 5 years ago.
I am learning synchronization in java. Got struck in the below sample code today.
In the below code, test() method is made synchronized. So, I assume th1's test() invocation would complete and then th2's test() invocation would start. However, it is not happening that way. The outputs are interweaved. Can you please help me understand why ?
public class MyThread {
public static void main(String[] args)
{
SampleThread sample = new SampleThread("one");
Thread th = new Thread(sample);
th.start();
SampleThread sample2 = new SampleThread("two");
Thread th2 = new Thread(sample2);
th2.start();
}
}
class SampleThread implements Runnable
{
public SampleThread(String name)
{
this.name=name;
}
String name;
#Override
public void run() {
test();
}
public synchronized void test()
{
for(int j=0;j<10;j++)
{
System.out.println(name + "--" + j );
}
}
}
To sync threads you need common point to sync them. Create object, pass it to the threads, then you can syncronize on the object. If you need to wait on the object in first thread, and notify in second. First example from google.
The method test() is synchronized but it isn't invoked by multiple threads cause each thread has a distinct instance of SampleThread. Use a single SampleThread for both threads to get subsequent output.
public class MyThread {
public static void main(String[] args) {
final SampleThread sample = new SampleThread();
Thread th = new Thread(sample);
th.start();
Thread th2 = new Thread(sample);
th2.start();
}
}
class SampleThread implements Runnable {
#Override
public void run() {
test();
}
public synchronized void test() {
for (int j = 0; j < 10; j++) {
System.out.println(Thread.currentThread().getId() + "--" + j);
}
}
}
I am working with the synchronization threads where I have three synchronized method and each method will access by individual thread (Total 3 threads in current program )
In our program we are calling one syn method is calling another sync method, below is sample code which is inspired from real application :
public class ThreadTest {
public static synchronized void suncMessage() {
System.out.print("1");
}
public static synchronized void suncMessage2() {
suncMessage();
System.out.print("2");
}
public static synchronized void suncMessage3(String s) {
System.out.print("3m" + s);
}
public static void main(String... at) throws InterruptedException {
Thread t1 = new Thread() {
public void run() {
for (int i = 0; i <= 2; i++) {
suncMessage();
}
}
};
Thread t2 = new Thread() {
public void run() {
for (int i = 0; i <= 2; i++) {
suncMessage2();
}
}
};
Thread t3 = new Thread() {
public void run() {
for (int i = 0; i <= 2; i++) {
suncMessage3("3");
}
}
};
t1.start();
t2.start();
t3.start();
}
}
So my question is, what is impact of calling one synch. method from another synch.?? Is it good practices and how it will impact the complexity of program?
Nice question, but you have to try hard when you are working on this type of scenarios and the performance may effect. Because synchronization is approx 50 time slower than normal method.
Im new to Threads and I was wondering how could I define what two or more different Threads do in a Java program. Do i define them all in the same public void run method? If so, how do I do it? I would like the Threat t1 to invoke the increment method, t2 to invoke the decrement method and both of them to call the value method
Here's the code example:
package interference;
/**
*
* #author rodrigopeniche
*/
public class Interference implements Runnable{
/**
* #param args the command line arguments
*
*/
Counter counter1= new Counter();
class Counter{
private int c= 0;
public void increment()
{
c++;
}
public void decrement()
{
c--;
}
public int value()
{
return c;
}
}
public static void main(String[] args) {
// TODO code application logic here
Thread t1= new Thread(new Interference());
Thread t2= new Thread(new Interference());
t1.start();
t2.start();
}
#Override
public void run() {
counter1.increment();
counter1.decrement();
counter1.value();
}
}
You can set names to threads like thread1, thread2. After that, in the run method, check the name of the thread currently running and do the necessary action.
You have to add a while loop inside the run method if you need to run it longer.
public static void main(String[] args) {
Interference interference = new Interference();//create a new Interference object
Thread t1 = new Thread(interference, "thread1");//pass the runnable interference object and set the thread name
Thread t2 = new Thread(interference, "thread2");//pass the runnable interference object and set the thread name
t1.start();
t2.start();
}
#Override
public void run() {
while (true) {//to run it forever to make the difference more visual
String threadName = Thread.currentThread().getName();//get the current thread's name
if (threadName.equals("thread1")) {//if current thread is thread1, increment
counter1.increment();
} else if (threadName.equals("thread2")) {//if current thread is thread2, decrement
counter1.decrement();
}
System.out.println(counter1.value());//print the value
}
}
When you run the code, you can see count is going up and down in a random manner.
In your current code, counter1 is an instance variable of class Interference. You create 2 instances of Interference and then use them to create two Thread objects. When the threads start to run, each Thread is actually working on it's own copy of counter1. I think that may not be what you expect.
package interference;
public class Interference {
static class Counter {
private int c = 0;
public void increment() {
c++;
}
public void decrement() {
c--;
}
public int value() {
return c;
}
}
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(new Runnable() {
public void run() {
counter.increment();
System.out.println(counter.value());
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
counter.decrement();
System.out.println(counter.value());
}
});
t1.start();
t2.start();
}
}
I am trying to write Thread Interference Example.
Below is my code:
class Counter {
private int c = 0;
public void increment() {
c++;
}
public void decrement() {
c--;
}
public int value() {
return c;
}
}
Suppose Thread A invokes increment at about the same time Thread B invokes decrement.
How to implement this one.
There is not guarantee how they will run it depends on OS scheduler. There is nothing better than this
Thread a = new ThreadA();
Thread b = new ThreadB();
a.start();
b.start();
To get two threads to start executing at the same time you can use a latch. (Which is to say, two threads that become available for execution as close together as possible.) Still for a single increment/decrement each it will probably take many runs to observe an interference. For a repeatable experiment you probably want to call increment/decrement several times in parallel and observe the final value of c.
final Counter counter = new Counter()
final CountDownLatch latch = new CountDownLatch(1);
Thread thread1 = new Thread(new Runnable() {
public void run() {
latch.await();
for (int i = 0; i < 100; i++) {
counter.increment();
}
}}).start():
Thread thread2 = new Thread(new Runnable() {
public void run() {
latch.await();
for (int i = 0; i < 100; i++) {
counter.decrement();
}
}}).start():
Thread.sleep(10);//give thread 2 a timeslice to hit the await
latch.countDown();
System.out.println(counter.value()); //non-zero value indicates interference
Now in this example if you try to execute and the output false shows interference.
How it works:
Both the Runnables keep a thread local count which is incremented for each invocation of increment() and decrement(). So after execution for some amount of time if we try to validate the values
Then you can say that:
value of Counter = invocation of increment() - invocation of decrement().
But when you try to verify this at the end of execution you get false. Which shows that the actual counter value was not as expected.
public static void main(String[] args) throws InterruptedException
{
Counter c = new Counter();
IncrementingRunnable incRunnable = new IncrementingRunnable(c);
DecrementingRunnable decRunnable = new DecrementingRunnable(c);
Thread tA = new Thread(incRunnable);
Thread tB = new Thread(decRunnable);
tA.start();tB.start();
Thread.sleep(10000);
stop = true;
tA.join();
tB.join();
//verify value
int actualCount = c.c;
int expectedCount = incRunnable.count - decRunnable.count;
System.out.println(actualCount == expectedCount);
}
public static volatile boolean stop = false;
static class IncrementingRunnable implements Runnable{
volatile int count = 0;
private Counter counter;
public IncrementingRunnable(Counter c) {
this.counter = c;
}
#Override
public void run() {
while(!stop){
counter.increment();
count++;
}
}
}
static class DecrementingRunnable implements Runnable{
volatile int count = 0;
private Counter counter;
public DecrementingRunnable(Counter c) {
this.counter = c;
}
#Override
public void run() {
while(!stop){
counter.decrement();
count++;
}
}
}
Now try changing the primitive c in Counter to AtomicInteger and see the output again. You will find that now the output is true.