Multi-threading in java
Have been trying to learn how to write multi-threaded programs in java and got stuck on a nice problem yesterday. The program below tries to start multiple threads and each one is supposed to print its name within brackets. To prevent the output getting garbled, the display method has been declared as synchronized. However, the output is still garbled such as:
{{{{T3T4T2T1}}}} instead of coming out as:
{T1}
{T2}
{T3}
{T4}
Here's the code, guess where the bug is:-)
import java.lang.*;
import java.util.*;
class myThread implements Runnable
{
String tname;
int priority;
Thread t;
myThread(String tn, int p)
{
tname = tn;
priority = p;
t = new Thread(this, tname);
t.setPriority(p);
}
public void run()
{
try {
display();
}
catch(Exception e) {;}
}
public void start()
{
System.out.println("Thread "+tname+" started with priority "+priority);
t.start();
}
synchronized void display() throws Exception
{
System.out.print("{");
Thread.sleep(1000);
System.out.print(tname);
Thread.sleep(1000);
System.out.println("}");
}
}
class TestThread
{
public static void main(String[] args) throws Exception
{
int n= new Integer(args[0]);
int x = n;
myThread[] thr = new myThread[5];
Thread.currentThread().setPriority(10);
while(x >0) {
thr[x] = new myThread("T"+x, 2*(n-x+1));
x--;
}
System.out.println("Main thread start");
for (x=n;x>0;x--) {
thr[x].start();
}
for (x=n;x>0;x--) {
thr[x].t.join();
}
System.out.println("Main thread end");
}
}
{{{{T3T4T2T1}}}} instead of coming out as:
{T1}
{T2}
{T3}
{T4}
Here's the code, guess where the bug is:-)
import java.lang.*;
import java.util.*;
class myThread implements Runnable
{
String tname;
int priority;
Thread t;
myThread(String tn, int p)
{
tname = tn;
priority = p;
t = new Thread(this, tname);
t.setPriority(p);
}
public void run()
{
try {
display();
}
catch(Exception e) {;}
}
public void start()
{
System.out.println("Thread "+tname+" started with priority "+priority);
t.start();
}
synchronized void display() throws Exception
{
System.out.print("{");
Thread.sleep(1000);
System.out.print(tname);
Thread.sleep(1000);
System.out.println("}");
}
}
class TestThread
{
public static void main(String[] args) throws Exception
{
int n= new Integer(args[0]);
int x = n;
myThread[] thr = new myThread[5];
Thread.currentThread().setPriority(10);
while(x >0) {
thr[x] = new myThread("T"+x, 2*(n-x+1));
x--;
}
System.out.println("Main thread start");
for (x=n;x>0;x--) {
thr[x].start();
}
for (x=n;x>0;x--) {
thr[x].t.join();
}
System.out.println("Main thread end");
}
}
0 Comments:
Post a Comment
<< Home