子线程:
class TestThread extends Thread
{
int total;
public void run()
{
for (int i=1;i<=30;i++ )
{
total += i;
System.out.println("子线程:"+total);
}
}
}
主线程:
class Demo
{
public static void main(String[] args)
{
TestThread demo=new TestThread();
demo.start();
int total=0;
synchronized(demo)
{
for (int i=1;i<=30;i++ )
{
total += i;
System.out.println("主线程:"+total);
}
}
System.out.println("执行完毕...");
}
}
预计的执行结果是:主线程执行完毕后,跳出synchronized块开始执行子线程
实际的执行结果时:子线程和主线程交替执行
这是为什么呢?我不是已经将子线程对象加锁了么?
研究了一下,我也不是很懂,给你说一下我的想法。首先这个同步是两个线程同时访问同一个变量时才需要使用的,也就是涉及到线程安全问题时使用synchronized关键字。你的这个可以说是只是为了测试,代码本身貌似没有同步的意义。
好像错误是出在了那个锁上,你的那个锁没有意义。子线程根本不需要那个锁就可以执行,所以子线程不会被阻塞。我是这么实现的,你看一下。
前辈你好,子线程为什么不需要demo也可以执行啊?我已经把demo锁起来了还可以执行?不科学啊,我其实就是想看到子线程不能执行的效果,但是不知道为什么还是会执行
追答demo只是你new出来的一个对象,子线程为什么要使用他才能执行呢?这个demo对象只不过是调用的一下Thread的start方法,在具体的run方法里面根本就没有使用这个demo,如果打算让子线程不执行,那就像我那么做,定义一个锁,然后在子线程的run方法里,写上 synchronized(Lock.class),这样子线程要是执行必须拿到这把锁,同时在主线程里先把这个锁使用了,这样子线程就不会执行了吧.....你可以查阅一下相关资料。这是我对这个锁的理解。