Hi everyone. As the title says I have a question about threads.
I have a static method that print chars. I create five threads tha call the methods but I don't mixing of chars in the output.
is that because the printing method is static? I wrote a loop that repeat the printing to see if some chars can mix with other but it doesn't seems so.
here is the code:
public class PrintThread implements Runnable{
private char c;
private int n;
public PrintThread(char c, int n)
{
this.c = c;
this.n =n;
}
public static void print(char c, int n)
{
for (int i=0;i<n; i++)
{
System.out.print(c);
}
}
and the main starter:
import java.lang.Thread;
/**
*
* @author Lior B
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
char[] chars = {'a','b','c','d','e'};
Thread[] threads = new Thread[5];
for (int j=0;j<500000;j++)
{
System.out.println();
for (int i=0;i<5;i++)
{
threads = new Thread(new PrintThread(chars,i+1));
threads.start();
}
System.out.print(":main:");
}
}
}
I always get a out put like:
eeeeebbacccdddd:main:
eeeeeabb:main:
ddddccceeeeebba:main:
ccceeeeebb:main:
ddddadddd:main:
cccaeeeeeccceeeeebbbbddddaccc:main:
eeeeedddda:main:
ccceeeeebbddddabbccc:main:dddd
eeeeeabbccc:main:
but never acdcdcdeeded...
is is just in this case or intermixing can never be achieved?
So is the printing a thread safe? and if not then why don't I get intermixing of chars?
I have a static method that print chars. I create five threads tha call the methods but I don't mixing of chars in the output.
is that because the printing method is static? I wrote a loop that repeat the printing to see if some chars can mix with other but it doesn't seems so.
here is the code:
public class PrintThread implements Runnable{
private char c;
private int n;
public PrintThread(char c, int n)
{
this.c = c;
this.n =n;
}
public static void print(char c, int n)
{
for (int i=0;i<n; i++)
{
System.out.print(c);
}
}
and the main starter:
import java.lang.Thread;
/**
*
* @author Lior B
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
char[] chars = {'a','b','c','d','e'};
Thread[] threads = new Thread[5];
for (int j=0;j<500000;j++)
{
System.out.println();
for (int i=0;i<5;i++)
{
threads = new Thread(new PrintThread(chars,i+1));
threads.start();
}
System.out.print(":main:");
}
}
}
I always get a out put like:
eeeeebbacccdddd:main:
eeeeeabb:main:
ddddccceeeeebba:main:
ccceeeeebb:main:
ddddadddd:main:
cccaeeeeeccceeeeebbbbddddaccc:main:
eeeeedddda:main:
ccceeeeebbddddabbccc:main:dddd
eeeeeabbccc:main:
but never acdcdcdeeded...
is is just in this case or intermixing can never be achieved?
So is the printing a thread safe? and if not then why don't I get intermixing of chars?