You are here:

Java/Threads in java

Advertisement


Question
Hi !my doubts  are  based on below programme.
------------------------------------------------------------------

class C implements Runnable
{
public void f1()
{
System.out.println("Hi");
}
public void run()
{
f1();
}
synchronized void f2()
{
System.out.println("Hello");
}
}
class synchronized
{
public static void main (String args[])
{
C c1=new C();
Thread t1=new Thread(c1);
Thread t2=new Thread(c1);
t1.start();
t2.start();
}
}
--------------------------------
Here  c1 is object of class C.
I have accessed method f1  of object c1 by threads t1 and  t2.
My Doubt:
I want to access method f1 by thread t1 and f2 by thread t2.
Is it possible?
If possible please tell me

Answer
First, you can't name a class sunchronized. It's a keyword in Java.
Typically you would use 2 classes for 2 threads if you wanted them to behave differently. Since t1 and t2 are kept out of scope from run() you can't determine which t1 or t2 it is from. If you made these viewable by the thread then you could do this. E.g. you could move the Thread variables inside the C class.


class C implements Runnable {
  Thread t1;
  Thread t2;
  public void f1() {
     System.out.println("Hi");
  }

  public void run() {
     if(Thread.currentThread() == t1)
     f1();
  }

  synchronized void f2() {
     System.out.println("Hello");
  }
}
class synchroniz {
  public static void main(String args[]) {
     C c1 = new C();
     c1.t1 = new Thread(c1);
     c1.t2 = new Thread(c1);
     c1.t1.start();
     c1.t2.start();
  }
}

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.