• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic