请教高手关于Java 多线程同步的问题
import java.io.*;
import java.util.*;
class T1
{ private int i;
private String name;
public T1()
{ }
public int getInt()
{ return i;
} public void setInt(int i)
{ this.i=i;
this.i++;
} public String getName()
{ return name;
} public void setName(String name)
{ this.name=name;
} }
class TestClientThread extends Thread {
// private BufferedReader in;
// private PrintWriter out;
private static int threadcount = 0;
private String name=null;
private T1 t1;
private int j=0;
public static int threadCount() {
return threadcount;
}
public TestClientThread(String name,T1 t1) {
super(name);
this.name=name;
this.t1=t1;
this.t1.setName(name);
try {
start();
} catch(Exception e) {
}
}
public void run() {
synchronized(this)
{threadcount++;
System.out.println("Name =["+name+"] Create Threadcount=["+threadcount+"]");
} try {
Thread.sleep(400);
//skip help
for(int i = 0; i < 3; i++) {
t1.setInt(i);
System.out.println("Thread Name =["+name+"] i=["+t1.getInt()+"] Obj Name=["+t1.getName()+"]");
}
j++;
Thread.sleep(100);
System.out.println("Thread Name =["+name+"] Current J=["+j+"]");
} catch(Exception e) {
//System.err.println("["+id+"] Exception : "+e);
} finally {
synchronized(this)
{ threadcount--; // Ending this thread
System.out.println("Current Threadcount=["+threadcount+"]");
}
}
} }
public class Test {
public static int MAX_THREADS = 100;
private static Random random = new Random();
public static void main(String[] args)
throws IOException, InterruptedException {
int i=0;
do {
i++;
if(TestClientThread.threadCount() < MAX_THREADS)
{ T1 t1=new T1();
new TestClientThread(String.valueOf(i),t1);
} else
break;
Thread.currentThread().sleep(random.nextInt(100));
} while(i<=100);
System.out.println("All "+MAX_THREADS+" clients are rexit!");
}
private static int getSleepTime() {
return 200;
} }
疑惑的问题如下:
1:在TestClientThread定义的私有对象t1,j是否需要同步?
2:对对象t1操作是否是线程安全的?例如调用t1的SET,GET方法
3:threadcount这个STATIC 变量是应该同步的吗?
4:那么在哪里产生的对象或者变量需要同步呢?
5:在设计多线程程序的时候,应该怎么考虑运行效率的问题呢?
请指点,在这个测试程序里面是否有不安全的线程代码,因本人是刚开始学习,有点迷惑。
THANKS。