0

guys i9 know it is dummy qustion but i am beginner .. i have this class

public class threadLocal {
private static ThreadLocal<String> myThreadLocal;

public threadLocal(){
    myThreadLocal = new ThreadLocal<String>();
}

public static ThreadLocal<String> getMyThreadLocal() {
    return myThreadLocal;
}

public static void setMyThreadLocal(ThreadLocal<String> myThreadLocal) {
    threadLocal.myThreadLocal = myThreadLocal;
}
}

and i want to call it like this in another class

myThreadLocal.setMyThreadLocal("patrick");

so what changes should i do in threadLocal class ??

6
  • yesss it is ... ithreadLlocal contatins object from ThreadLocal Commented Apr 6, 2016 at 8:50
  • 4
    If myThreadLocal is of type threadLocal you can't call setMyThreadLocal with the argument "patrick", because it expects an object of type ThreadLocal<String>, not an object of type String. Commented Apr 6, 2016 at 8:53
  • @ModusTollens so waht should changes i do to call it with argument patrick ?? Commented Apr 6, 2016 at 8:56
  • I'm not sure what you are trying to do, but you can change the method argument to receive a String and construct a ThreadLocal<String> object from that, or you keep the argument as type ThreadLocal<String> and call the method with an object of type ThreadLocal<String>. Commented Apr 6, 2016 at 8:58
  • Does the ThreadLocal class have a constructor that uses a String as arument? Commented Apr 6, 2016 at 8:59

1 Answer 1

3

I think you should rewrite your class this way.

public class threadLocal {
 private static ThreadLocal<String> myThreadLocal = new ThreadLocal<String>();

 public static String getMyThreadLocal() {
    return myThreadLocal.get();
  }

 public static void setMyThreadLocal(String str) {
    myThreadLocal.set(str);
  }
}

While calling, you may just call

threadLocal.getMyThreadLocal()
Sign up to request clarification or add additional context in comments.

4 Comments

and how call it in main class ??
threadLocal local = new threadLocal(); local.setMyThreadLocal("dsfd");
setMyThreadLocal is static, so you need to call the method on the class. So: threadLocal.setMyThreadLocal("patrick");
BTW the classnames in java usually start with Capital letter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.