线程的同步块是什么意思啊?
synchronized(Object)
{}
书上说是获得该Object的锁,但"该Object的锁"到底指什么呢?
书上又说如果获得了该Object的锁,别的线程就不能调用该Object中的synchronized方法,但如果该Object中没有synchronized方法呢?那么加了这个同步块又有什么意义呢?
万分感谢!
synchronized(Object)
{}
书上说是获得该Object的锁,但"该Object的锁"到底指什么呢?
书上又说如果获得了该Object的锁,别的线程就不能调用该Object中的synchronized方法,但如果该Object中没有synchronized方法呢?那么加了这个同步块又有什么意义呢?
万分感谢!
{
synchronized void display(int num)
{
System.out.print(""+num);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("中断");
}
System.out.println(" 完成");
}
}class Two implements Runnable
{
int number;
One one;
Thread t;
public Two(One one_num, int n)
{
one=one_num; number=n;
t=new Thread(this);
t.start();
}
public void run()
{
one.display(number);
}
}public class exec
{
public static void main(String args[])
{
One one=new One();
int digit=10;
Two s1=new Two(one,digit++);
Two s2=new Two(one,digit++);
Two s3=new Two(one,digit++);
try
{
s1.t.join();
s2.t.join();
s3.t.join();
}
catch(InterruptedException e)
{
System.out.println("中断");
}
}
}楼主 希望对你有帮助
synchronized(Object)
{}
这一块的时间中,其他需要synchronized(Object){ }的线程会因为拿不到这个对象的标志位,而继续等待.
可以将synchronized去掉以观察效果
控制并发线程只能互斥访问这一段代码
class AThread extends Thread {
static boolean threadSafe = true;
static int value = 0;
static int maxid = 0;
static Object o = "";
int thisid;
public AThread(int id) {
thisid = id;
} public void doSth() {
for (int j = 0; j < 10; ++j) {
int k = value + 1;
try { Thread.sleep(1);}catch (Exception e) {}
value = k;
}
if (maxid < thisid) maxid = thisid;
}
public void run() {
if (threadSafe)
synchronized (o) { doSth();}
else
doSth();
}
}class ThreadTest {
public static void main(String[] args) {
int maxThread = 10;
AThread.threadSafe = false; // comment out this line see different result
for(int i = 0; i < maxThread; ++i) {
new AThread(i+1).start();
}
while(AThread.maxid != maxThread)
try {Thread.sleep(1000); } catch (Exception e) {}
System.out.println("Thread Safe:"+AThread.threadSafe);
System.out.println(AThread.value);
}
}
========>
当一个线程没有退出同步块时,别的线程无法访问同步块中的任何方法.