Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within OCPJP
Search Coderanch
Advance search
Google search
Register / Login
Win a copy of
OCP Oracle Certified Professional Java SE 21 Developer Study Guide: Exam 1Z0-830
this week in the
Programmer Certification
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
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Tim Cooke
Liutauras Vilda
Jeanne Boyarsky
paul wheaton
Sheriffs:
Ron McLeod
Devaka Cooray
Henry Wong
Saloon Keepers:
Tim Holloway
Stephan van Hulst
Carey Brown
Tim Moores
Mikalai Zaikin
Bartenders:
Frits Walraven
Forum:
Programmer Certification (OCPJP)
Thread code produces different output
naveen yadav
Ranch Hand
Posts: 384
I like...
posted 13 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Following Code 1 and Code2 is expected to produce same output. Code 1 works as expected but code 2 does not.
Why Code 2 produces "11" every time.
Code 1
public class Pregnant extends Thread { int x = 0; public static void main(String[] args) { Runnable r1 = new Pregnant(); new Thread(r1).start(); new Thread(r1).start(); } public void run() { for(int j = 0; j < 3; j++) { x = x + 1; x = x + 10; System.out.println(Thread.currentThread().getName() +": " +x ); x = x + 100; } } }
Output values :
11
22
133
244
466
355
Code 2
public class Skip { public static void main(String[] args) throws Exception { Jump ob = new Jump(); Thread t1 = new Thread(ob); Thread t2 = new Thread(ob); t1.start(); t2.start(); } } class Jump implements Runnable { int ctr=0; public void run() { for(int i = 0; i < 3; i++) { ctr = ctr=+1; ctr = ctr+10; System.out.println(Thread.currentThread().getName() + "ctr ="+ctr); ctr = ctr+100; } } }
Output values : 11 six times . Why ?
Tim Moores
Saloon Keeper
Posts: 7645
178
posted 13 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
The problem is in line 18 of class Skip.
naveen yadav
Ranch Hand
Posts: 384
I like...
posted 13 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
yes it typing mistake. otherwise Both codes woks exactly same as expected.
thanks Tim
O. Ziggy
Ranch Hand
Posts: 430
I like...
posted 12 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
What was the mistake? i cant see it..
F is for finger. Can you stick your finger in your nose? Doesn't that feel nice? Now try this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
join() method in Thread doesn't work as expected
Shouldnt the output overlap?(Threading)
join()
Thread question
A thread of doubt
More...