Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

error message why?

 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

class SyncClass {

public synchronized void printSomething() {
for (int i=1; i<=3; i++) {
System.out.println(Thread.currentThread().getName()+" Print "+i);
try {
System.out.println(Thread.currentThread().getName()+" Sleep "+i);
Thread.sleep(500);
} catch(InterruptedException e) {
}
System.out.println(Thread.currentThread().getName()+" End "+i);
}
}
}

class ThreadTest {
public static void main(String[] args)
{
SyncClass sc = new SyncClass();
Thread t3 = new Thread(new Runnable() {
public void run()
{

sc.printSomething();
}
}, "A");

Thread t4 = new Thread(new Runnable(){
public void run()
{
sc.printSomething();
}
}, "B");

t3.start();
t4.start();
sc.printSomething(); // main called

}





C:\>javac ThreadTest.java
ThreadTest.java:24: local variable sc is accessed from within inner class; needs
to be declared final
sc.printSomething();
^
ThreadTest.java:31: local variable sc is accessed from within inner class; needs
to be declared final
sc.printSomething();
^
2 errors
 
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your are declaring two Runnable anonymous inner classes, which are trying to access a local variable. Any local variable used but not declared in an inner class must be declared final and definitely assigned before the body of the inner class.
 
What's gotten into you? Could it be this tiny ad?
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic