• Welcome! The TrekBBS is the number one place to chat about Star Trek with like-minded fans.
    If you are not already a member then please register an account and join in the discussion!

Java Question about threads and static methods

Lior .B.

Fleet Captain
Fleet Captain
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?
 
You can't make any assumptions about event ordering between threads except for those you enforce yourself. Beyond that, the implementation is free to do whatever it chooses.

Never assume anything is thread-safe unless it is documented to be thread-safe, or you have inspected it and found it to only use objects and operations you know are thread-safe. The fact that something may seem to work properly is not good enough evidence that it is actually correct.
 
thanks.
Yes I know that I can't assume that it is a thread safe.
What I like know is if I can get mix of chars with this code like "abcd:main:ebcdecdedee"..

I believe I can. it's probably just this instance of the output and in different instace they do intermix in some cases.
 
If you are not already a member then please register an account and join in the discussion!

Sign up / Register


Back
Top