Win a copy of Building Blockchain Apps this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Liutauras Vilda
  • Knute Snortum
  • Bear Bibeault
Sheriffs:
  • Devaka Cooray
  • Jeanne Boyarsky
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • salvin francis
Bartenders:
  • Tim Holloway
  • Piet Souris
  • Frits Walraven

error message why?

 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • 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
  • 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.
 
Everybody! Do the Funky Monkey! Like this tiny ad!
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!