Defining two different Threads in java - java

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();
}
}

Related

Thread loop - Extending Thread Class Java

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();
}
}

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();
}
}

How can I call a same method with three different thread

Suppose I have a method called Magic() I want to execute this method with three different thread.
I know how to execute Magic() method with a single thread, but I am confuse, How do I do with three different threads?
Suppose I have a method called Magic() I want to execute this method with three different thread
Create a MagicTask class that represents the task that each Thread will execute and call the magic() method inside run() :
class MagicTask implements Runnable {
public void run() {
magic();
}
public void magic() { //do magic }
}
Then create three threads and pass it the task :
Thread t1 = new Thread(new MagicTask());
Thread t2 = new Thread(new MagicTask());
Thread t3 = new Thread(new MagicTask());
Then start the threads :
t1.start();
t2.start();
t3.start();
Note You can pass the same MagicTask instance to all three Thread instances as well. Remember that if MagicTask has state that can get inconsistent when accessed by different threads, you also need to make your class thread-safe by using intrinsic locking using synchronized or other such constructs which are out of the scope for this answer.
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
call();
}
void call(){
System.out.println("method call by"+Thread.currentThread().getName());
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
Thread t2 =new Thread(m1);
Thread t3 =new Thread(m1);
t1.start();
t2.start();
t3.start();
}
}
Here Thread t1,t2,t3 are calling the same method call().
If you are using Java 8, function references are straightforward:
public class Main {
public static void magic() {
System.out.println("this is magic");
}
public static void main(final String args[]) {
new Thread(Main::magic).start();
new Thread(Main::magic).start();
new Thread(Main::magic).start();
}
}
And if magic isn't a static method use:
public class Main {
public void magic() {
System.out.println("this is magic");
}
public static void main(final String args[]) {
Main m = new Main();
new Thread(m::magic).start();
new Thread(m::magic).start();
new Thread(m::magic).start();
}
}
You can try Like.
I am dividing the task to different thread
Try your own logic it just a simple even count,
public class CountNumber implements Runnable {
int stop;
int start;
int totalEvenNo;
public CountNumber(int start, int stop)
{
this.start=start;
this.stop=stop;
}
public void run()
{
int total= countEven(start, stop);
System.out.println("Total Even numbers are :"+total);
}
public int countEven(int str,int stp)
{
for(int i=str;i<=stp;i++)
{
if(i%2==0)
{
totalEvenNo +=1;
System.out.println(totalEvenNo);
}
}
return totalEvenNo;
}
}
public class MainClassNumber {
public static void main(String[] args) {
System.out.println("Spawaning Thread.........");
Thread t1 = new Thread(new CountNumber(0, 500000));
Thread t2 = new Thread(new CountNumber(500001, 2000000));
Thread t3 = new Thread(new CountNumber(2000001, 5000000));
Thread t4 = new Thread(new CountNumber(5000001, 10000000));
Thread t5 = new Thread(new CountNumber(10000001, 20000000));
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
Call it directly like magic(); And for better result synchronize that method like below
public synchronized void magic(){
//your code
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {
public void run() {
Magic();
}
private void Magic() {
// consider synchronizing this method, but if you do method will be accessable by one thread at a time.
}
}
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3)
for (int i = 0; i < 3; i++) {
Runnable worker = new WorkerThread();
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {}
}
}
}

Threads execute not at the same time

I have three threads, each thread have to do some manipulation with the instance(q) of same class (Q), periodically (That's why I use Thread.sleep() in the method somecheck). Main task is to make thread execute not at the same time, so at one time can execute only one thread.
I tried to put content of run method each thread into synchronized (q){}, but I do not understand where to put notify and wait methods.
class Q {
boolean somecheck(int threadSleepTime){
//somecheck__section, if I want to stop thread - return false;
try{
Thread.sleep(threadSleepTime);
} catch (InterruptedException e) {
}
return true;
}
}
class threadFirst extends Thread {
private Q q;
threadFirst(Q q){this.q=q;}
public void run(){
do{
//Working with object of class Q
}
while(q.somecheck(10));
}
}
class threadSecond extends Thread {
private Q q;
threadSecond(Q q){this.q=q;}
public void run(){
do{
//Working with object of class Q
}
while(q.somecheck(15));
}
}
class threadThird extends Thread {
private Q q;
threadThird(Q q){this.q=q;}
public void run(){
do{
//Working with object of class Q
}
while(q.somecheck(20));
}
}
class run{
public static void main(String[] args) {
Q q = new Q();
threadFirst t1 = new threadFirst(q);
threadSecond t2 = new threadSecond(q);
threadThird t3 = new threadThird(q);
t1.start();
t2.start();
t3.start();
}
}
You don't need to put any notify() and wait() methods if you use synchronized blocks inside all of the methods, for example:
class threadFirst extends Thread {
...
public void run() {
synchronized (q) {
//your loop here
}
}
...
}

Multithreading - Synchronizing the block for all instances of an Object

I have a class as Calculate. I created two threads both working on different instances of this class and tried to get the value of i. But both are giving me same values.
I want if one thread of a instance is working then the thread working on other instance should wait.
public class Calculate {
private int i=2;
public void showNumber(){
synchronized(Calculate.class){
i=i+2;
}
System.out.println(Thread.currentThread()+"Value of i is "+i);
}
}
class Test1 implements Runnable{
Calculate c=null;
public Test1(Calculate c){
this.c=c;
}
#Override
public void run() {
System.out.println(Thread.currentThread()+" Running");
c.showNumber();
}
}
public class ThreadingPractise {
public static void main(String[] args) {
Calculate c=new Calculate();
Calculate c1=new Calculate();
Thread t1=new Thread(new Test1(c),"t1");
Thread t2=new Thread(new Test1(c1),"t2");
t1.start();
t2.start();
}
}
make i as static. If you want to share the variable between threads. and synchronize showNumber method instead of Calculate.class so that only 1 thread will run it at a time.

Categories