• Post Reply Bookmark Topic Watch Topic
  • New Topic

Create multiple Threads

 
Smilidon Sapiens
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I want to create an array of threads. Any thread should have a var x. The value of x should be different in any thread (random) and should increment. I tried this :
<code>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ThTest2 extends JFrame
{
public ThTest2 (String Title)
{
super (Title);
SubThread temp = new SubThread();
Thread[] th = new Thread[10];
for (int i = 0; i < 10; i++)
{
th[i] = new Thread(temp);
th[i].start();
}
addWindowListener(new WindowAdapter()
{
public void windowClosing (WindowEvent evt)
{
System.exit(0);
}
});
setSize(300, 300);
setVisible(true);
}

public static void main (String args[])
{
JFrame th = new ThTest2("ThTest2");
}
class SubThread extends Thread
{
int x;
public SubThread()
{
x = (int)(Math.random() * -30);
}
public void run()
{
while(true)
{
try
{
sleep(1000);
} catch (InterruptedException e) {}
System.out.println("X: " + x++);
}
}
}
}
</code>
All threads increase the same x-value. How can I create threads with individual x-values ???
Thanks for your help...
 
Smilidon Sapiens
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Problem solved :
<code>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ThTest2 extends JFrame
{
public ThTest2 (String Title)
{
super (Title);
SubThread[] th = new SubThread[10];
for (int i = 0; i < 10; i++)
{
th[i] = new SubThread(Integer.toString(i));
th[i].start();
}
addWindowListener(new WindowAdapter()
{
public void windowClosing (WindowEvent evt)
{
System.exit(0);
}
});
setSize(300, 300);
setVisible(true);
}

public static void main (String args[])
{
JFrame th = new ThTest2("ThTest2");
}
class SubThread extends Thread
{
int x;
String s;
public SubThread(String s)
{
this.s = s;
x = (int)(Math.random() * -30);
}
public void run()
{
while(true)
{
try
{
sleep(2000);
} catch (InterruptedException e) {}
System.out.println("ID : "+s+" X: " + x++);
}
}
}
}
</code>
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!