猿问

关于Runnable接口,多个线程共享一个target和实例变量的问题

public class SecondThread implements Runnable {	
    int i;
    @Override
    public void run() {
        for(;i<20;i++){
	    System.out.println(Thread.currentThread().getName()+"-"+i);
	}
    }
    public static void main(String[] args) {
	for(int i=0;i<20;i++){
	    System.out.println(Thread.currentThread().getName()+"-"+i);
	    if(i==10){
	        SecondThread st=new SecondThread();
		    new Thread(st,"线程1").start();
		    new Thread(st,"线程2").start();
	    }
	}
    }

}

输出结果中 线程1和线程2后面的i应该是共享的并且连续的,如线程2-0、线程1-1、线程1-2、线程2-3、线程1-4、线程1-5、线程2-6...

但我跑了很多次,发现每次线程1和线程2都会输出0:线程1-0,线程2-0。但后面的数字就是连续交替的的,为什么偏偏这个0都会输出一次?

慕粉4241372
浏览 1938回答 2
2回答

慕瓜9220888

SAIKTCZPFKBWOQQQMFHIAMRKQXGFNVNLQTMPHOAPQLLOYKHDIXAQDMJNYAFXGQZPTLDMFYIYEYKZBHQNWQPRJPZIIUBJUBATMZIZQSXGOKXTCWVTLLEYUYFOJIFOBEZTSFESIVHQHGINYRKKNEMLADZJVABKVATGWZMDSUZCXAKLMBTVRUHQLWEAFYVEHLWHCLBXHVOMBDILRCFENFXTMFYOHCAPXHAQTULNLZSIOYUPXZKXHNNOFUFSCOVRTXWHQGSVLXBHNQAZCWWNSNFPOYHZWLXFILVHDECOAMZHNEZYQVBBHHEODPERUTWEVRZRLZCIXDVNCOBBHLZLNCLRHTUFHWRBNHQEFUWOERSJEOLRPZSSEJEMRTQZMFUBSHTWBXKIFUQVOHEXCQSATWZPIRSCUCVSEIFGYAIFYBEGOQIGJJMPLGLIUUQQGYRTIKDMZJFJEWYRBUBKOXGPGDTKSSBQZTQRRUSOXQGNNOJEDCLIZPARGJSBRYVCQVXMVSTTKQMVENXUBVBJCRNEDXHESRRAGHZTOWLUTAKCEPGOWYLBUATRTCBMTBCBMRBWWJZJFQVNRXKJGBLVACTGZSYTOTODGGCGQGFYUKJIDHKPFCUEFDOTOTATIYRWBJILBEANECEDGGJMBCUTSLERQARGYTQMGJJEZKLLUQQZUWBJCHKDTRMEGPSIHITSNISYLOGOJIXDDCJWHZHJSTNAISOQRBOHBZVUZUOKHJBVQUCCBBHZKJLZTMXGZHSHZMMILVQSUJLFOVMDCHQPSCIRSUMVERRXABIDSFLHBTLQWPCLMCXCRZBHATQKIRMRUNQGMNMRZPMEKRWXGYRREXIZBQCLVHUKBQGFIVLKPQFAZICTYUBBEMPFMZUKFUAZCSFYAYGLEHUEUVHMHDNRXETVKKQCCDIMYNZMJJSUBNIONLDJBZHDVOHRURONPKUQGJUGFXVYRUOYVDBPMPVBZTBQPIBYHJUFBTWFPLPGOZIIEKHELRGLXQQNKJYNDJKEEPHJCBQQXYKADCUIFMMUYHKPDTARWBAJWDUULGOXGPYEPZIOXGFVCPACKJSEHOBMWLHVBADDICTIGYYJGPMWLHMPAKDGHDEDILBEIJUJFOUFCQHMYQZGZCVMBASVHHEIEDYKTNQWQYCACIVFRDOWEXDJCXQAWLNGCFYOZOJIRKEXNEEAFLRERNLUWVGTKQURDSKHGIVUFTCUXGZJOLKCRENQWRYHSXQANWUVFRJZSPPOFEWEXKUCTNVKGPVKKVMOMBEPVIVMYTCVLIYIGYDVISOYCGHMCSDTKCTSNSVNTDJKCLTQEXEGEGLQWMMJABQOGGTPXNOQSHKDAZNOGYNAZJPWHGRQDQZJESRLJTFIYYWRGYNXJTXPHPRANXGZRWFEVPFDZABXPKNQQOFUGUOXTLXQBLQANDPVZBNIBKRABCKMHNNQTNUGVQGWJMXYJOWDJPZGNCHHKTWMRINVNHOBREZOPYRKKNYATCRWXALGDWYJGMFKDXWYWZSICVMYQIRABIDEDLXSYXUIDVDCLELUNOTVANWZWKVXCOUXAZOCOWEKRQUNYYHPIYFVULGFUHAAWQEZRXDNTQGRTIQDMGPRLQMHOQKN

半枯

你这还算是好的,如果你不是写for对i的判断进行小于20的判断,而是通过if判断某个值,那么就会出现超值,就是一直跑下去.

慕娘0009941

首先 i++ 本身并不是一个原子操作,其次还存在内存可见的问题。比较简单的解决方法有两种都可以达到你想要的效果 (1)用 volatile 关键字 修饰共享变量 i   (2)将 i 的访问都封装到一个方法里,并用 synchronized 添加同步保护
随时随地看视频慕课网APP

相关分类

Java
我要回答