看到群里有人发出两个面试问题,写了下第7题的线程题目,得出了答案,把代码贴出来,以后自己常来看看,写写东西。话说这是我写的第一篇博客,有点O(∩_∩)O!
以下是第7题的答案
PRivate ActivityMyAppleForBinding binding; List<HashMap<String,String>> list=new ArrayList<>(); List<String> listkey=new ArrayList<>(); Thread t1,t2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);// binding=DataBindingUtil.setContentView(this,R.layout.activity_my_apple_for);// recyclerview_item_apply_job HashMap<String,String> map1=new HashMap<>(); map1.put("macBookPro","8988"); list.add(map1); HashMap<String,String> map2=new HashMap<>(); map2.put("三星note7","5675"); list.add(map2); HashMap<String,String> map3=new HashMap<>(); map3.put("小米4","2688"); list.add(map3); HashMap<String,String> map4=new HashMap<>(); map4.put("联想p612","866"); list.add(map4); HashMap<String,String> map5=new HashMap<>(); map5.put("iphone7","5688"); list.add(map5); listkey.add("macBookPro"); listkey.add("三星note7"); listkey.add("小米4"); listkey.add("联想p612"); listkey.add("iphone7"); TestTask testTask=new TestTask(); t1=new Thread(testTask); t2=new Thread(testTask); t1.start(); t2.start(); } public class TestTask implements Runnable{ //执行线程 @Override public void run() { //抽取次数不做限制,直到奖品抽完为止 while (listkey.size()>0){ int size=listkey.size(); //随机抽取出的奖品 int number = new Random().nextInt(size); String key=listkey.get(number);// String value=list.get(number).get(key); listkey.remove(number);// list.remove(number); Log("+++++++"+Thread.currentThread().getName()+"------key--"+key); Log("----t1-----"+t1.getName()); Log("----t2-----"+t2.getName());// 02-07 10:49:57.978 27727-29735/org.unionapp.xfjyw E/LOG: +++++++Thread-4083------key--iphone7// 02-07 10:49:57.979 27727-29735/org.unionapp.xfjyw E/LOG: ----t1-----Thread-4083// 02-07 10:49:57.979 27727-29735/org.unionapp.xfjyw E/LOG: ----t2-----Thread-4084// 02-07 10:49:57.979 27727-29735/org.unionapp.xfjyw E/LOG: +++++++Thread-4083------key--三星note7// 02-07 10:49:57.979 27727-29735/org.unionapp.xfjyw E/LOG: ----t1-----Thread-4083// 02-07 10:49:57.979 27727-29736/org.unionapp.xfjyw E/LOG: +++++++Thread-4084------key--macBookPro// 02-07 10:49:57.979 27727-29736/org.unionapp.xfjyw E/LOG: ----t1-----Thread-4083// 02-07 10:49:57.979 27727-29736/org.unionapp.xfjyw E/LOG: ----t2-----Thread-4084// 02-07 10:49:57.979 27727-29736/org.unionapp.xfjyw E/LOG: +++++++Thread-4084------key--联想p612// 02-07 10:49:57.979 27727-29736/org.unionapp.xfjyw E/LOG: ----t1-----Thread-4083// 02-07 10:49:57.979 27727-29736/org.unionapp.xfjyw E/LOG: ----t2-----Thread-4084// 02-07 10:49:57.980 27727-29735/org.unionapp.xfjyw E/LOG: ----t2-----Thread-4084// 02-07 10:49:57.981 27727-29736/org.unionapp.xfjyw E/LOG: +++++++Thread-4084------key--小米4// 02-07 10:49:57.981 27727-29736/org.unionapp.xfjyw E/LOG: ----t1-----Thread-4083// 02-07 10:49:57.981 27727-29736/org.unionapp.xfjyw E/LOG: ----t2-----Thread-4084 } } }有点乱,可以多试几种方法去解答,再去多学习下线程的东西,来做总结。
新闻热点
疑难解答