线程编程中踩的坑(一)

今天在进行线程编程中踩了一个坑

先看一个无聊的例子:

public class Myt {
	static boolean stop=false;
	public static void main(String[] args) throws InterruptedException {
		Thread thread =new Thread() {
			@Override
			public void run() {
				int i=1;
				while(!stop) {
						i++;
				}
				System.out.println("22-----i="+i);
			}
		};
		thread.start();
		Thread.sleep(2000);
		stop=true;
		System.out.println("11");
		thread.join();
		System.out.println("33");
	}
}

程序定义了一个线程,线程会不停的判断stop标志位,如果为真则循环累加i。然后我们在主线程里面修改stop为true。期望线程在进行2秒之后停止。

如果了解过内存屏障多级存储的那么就很容易的知道:运行这个程序我们得到的结果是——程序永远不会停止。主线程main里面修改的变量在thread里面并没有发生改变(thread里面没有重新在内存中读取修改后的值)。

那么把代码稍微修改一下:

public class Myt {
	static boolean stop=false;
	public static void main(String[] args) throws InterruptedException {
		Thread thread =new Thread() {
			@Override
			public void run() {
				int i=1;
				while(!stop) {
                        System.out.println(i);
						i++;
				}
				System.out.println("22-----i="+i);
			}
		};
		thread.start();
		Thread.sleep(2000);
		stop=true;
		System.out.println("11");
		thread.join();
		System.out.println("33");
	}
}

其实就是在thread线程的循环里面加了一个System.out.println(i),每循环一遍都吧 i 的值输出一遍。

那么运行这个程序,这个程序还会是永远不会停止的么?有兴趣的朋友可以运行一遍试下。

答案是这个循环会被跳出,也就是说程序会停止。

刚发现这个问题的时候我想了很久,也尝试用其他语句替换掉System.out.println(i),比如定义一个变量,执行一个方法等,发现都不能使程序停止,那么问题就出在了println方法中,发现了问题那么原因就好找了。

我们先来看看println方法

/**
     * Prints an integer and then terminate the line.  This method behaves as
     * though it invokes <code>{@link #print(int)}</code> and then
     * <code>{@link #println()}</code>.
     *
     * @param x  The <code>int</code> to be printed.
     */
    public void println(int x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }

看到这里估计很多人都发现了吧,没错就是synchronized同步块,所有同步在一个对象上的同步块在同时只能被一个线程进入并执行操作。所有其他等待进入该同步块的线程将被阻塞,直到执行该同步块中的线程退出。进入、离开同步代码块,都会和主内存的共享变量的值保持一致。也就是说同步块中的变量都会进行变量同步,同步块中的变量都会重新在内存中读取,即能读到主线程main修改后的值。所以在thread线程的循环里面加了一个System.out.println(i)输出,循环才会因为读到了修改后的值而退出。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值