id
stringlengths
36
36
text
stringlengths
1
1.25M
04dbe1fc-e2fc-4c83-8d48-3637c9433bc3
public static List<Map> grabMeiziPhoto(int pageNumber) throws IOException, ParseException { List<Map> result = new ArrayList<Map>(); SimpleDateFormat dateConvert = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String pageUrl = Const.chunTuMeiziPageUrl + pageNumber; String pageContent = NetUtil.getPageSource(pageUrl); Pattern pattern = Pattern.compile(RegexUtil.chunTuMeiziRegex); Matcher matcher = pattern.matcher(pageContent); int counter = 1; while (matcher.find()) { Map photo = new HashMap(); photo.put("description", matcher.group(1)); photo.put("id", matcher.group(2)); photo.put("date", dateConvert.parse(matcher.group(3))); photo.put("imgUrl", matcher.group(4)); result.add(photo); counter++; } return result; }
cf6232cb-e716-4ddd-8df7-1ac8dffa5b91
public static List<Map> grabMeinvPhoto(int pageNumber) throws IOException, ParseException { List<Map> result = new ArrayList<Map>(0); SimpleDateFormat dateConvert = new SimpleDateFormat("yyyy年MM月dd日"); String pageUrl = Const.chunTuMeinvPageUrl + pageNumber; String pageExtUrl = Const.chunTuMeinvExtPageUrl + pageNumber; Map paras = new HashMap(); paras.put("p", "1"); String pageContent = NetUtil.getPageSource(pageUrl); pageContent += NetUtil.getPageSourceByHTTPClientPost(pageExtUrl, "www.chuntu.cc", pageUrl, null, paras); pageContent = pageContent.replaceAll("(\r\n|\r|\n|\n\r)", "<br>"); Pattern pattern = Pattern.compile(RegexUtil.chunTuMeinvRegex); Matcher matcher = pattern.matcher(pageContent); int counter = 1; while (matcher.find()) { Map photo = new HashMap(); photo.put("id", matcher.group(1)); photo.put("imgUrl", matcher.group(2).replace("200", "600")); photo.put("date", dateConvert.parse("2013年" + matcher.group(3))); result.add(photo); counter++; } return result; }
682c129b-f79f-44c6-abd3-1bdcfdd407ad
public static List<Map> grabTuwenPhoto(int pageNumber) throws IOException, ParseException { List<Map> result = new ArrayList<Map>(0); SimpleDateFormat dateConvert = new SimpleDateFormat("yyyy年MM月dd日"); String pageUrl = Const.chunTuTuwenPageUrl + pageNumber; String pageExtUrl = Const.chunTuTuwenExtPageUrl + pageNumber; Map paras = new HashMap(); paras.put("p", "1"); String pageContent = NetUtil.getPageSource(pageUrl); pageContent += NetUtil.getPageSourceByHTTPClientPost(pageExtUrl, "www.chuntu.cc", pageUrl, null, paras); pageContent = pageContent.replaceAll("(\r\n|\r|\n|\n\r)", "<br>"); Pattern pattern = Pattern.compile(RegexUtil.chunTuTuwenRegex); Matcher matcher = pattern.matcher(pageContent); int counter = 1; while (matcher.find()) { Map photo = new HashMap(); photo.put("id", matcher.group(1)); photo.put("imgUrl", matcher.group(2).replace("200", "600")); photo.put("description", matcher.group(3)); photo.put("date", dateConvert.parse("2013年" + matcher.group(4))); result.add(photo); counter++; } return result; }
90aab57b-13d0-4cd2-9cca-28f7f047977c
public static List grabTaoTuIds(int pageNumber) throws IOException { String pageUrl = Const.chunTuTaotuPageUrl + pageNumber; String pageContent = NetUtil.getPageSource(pageUrl); Pattern pattern = Pattern.compile(RegexUtil.chunTuTaotuRegex); Matcher matcher = pattern.matcher(pageContent); List taotuIds = new ArrayList(); while (matcher.find()) { taotuIds.add(matcher.group(1)); } return taotuIds; }
82b0518a-ef50-48a9-a517-3a5c6bc26e48
public static List<String> grabTaoTuPhotosById(int id) throws IOException { List result = new ArrayList(); String pageUrl = Const.chunTuTaotuDetailPageUrl + id; String pageContent = NetUtil.getPageSource(pageUrl); Pattern pattern = Pattern.compile("data-original=\"(.*?)\""); Matcher matcher = pattern.matcher(pageContent); while (matcher.find()) { result.add(matcher.group(1)); } return result; }
395f8ace-b160-4c2a-89f0-abcbd798cd38
public static void grabPhoto(int pageNumber) throws IOException { String pageUrl = Const.s91MeiTuPageUrl + pageNumber + "0"; String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.10 (KHTML, like Gecko) Chrome/23.0.1262.0 Safari/537.10"; String pageContent = NetUtil.getPageSourceByHTTPClient(pageUrl, "www.91meitu.net", "http://www.91meitu.net/", userAgent); Pattern pattern = Pattern.compile(RegexUtil.s91MeiTuRegex); Matcher matcher = pattern.matcher(pageContent); int counter = 1; while (matcher.find()) { String imgUrl = matcher.group(1); imgUrl = imgUrl.replace("filename\":\"","http://meitu91.b0.upaiyun.com/"); System.out.println("第" + counter + "张:"); System.out.println(imgUrl); counter++; } }
048f53d5-08a2-40e5-9988-e46dafe2ddc7
public static void grabPetOldPhoto(Object lastPinId, int totalCount) throws IOException { String pageUrl = Const.huaBanPetOldPageUrl; for (int index = 0; index < totalCount; index++) { pageUrl = pageUrl + lastPinId; String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.10 (KHTML, like Gecko) Chrome/23.0.1262.0 Safari/537.10"; String pageContent = NetUtil.getPageSourceByHTTPClient(pageUrl, "huaban.com", "http://huaban.com/", userAgent); List pins = (List) ((Map) JsonUtil.getMap4Json(pageContent)).get("pins"); int counter = 1; for (int i = 0; i < pins.size(); i++) { Map pin = (Map) pins.get(i); String key = (String) ((Map) pin.get("file")).get("key"); key = "http://img.hb.aicdn.com/" + key; Object pinId = pin.get("pin_id"); lastPinId = pinId; System.out.println(pinId + " | " + counter + " : " + key); counter++; } } }
de7a21c5-308d-4dde-9a67-cc0adad2b94d
public static void grabPetNewPhoto(Object lastPinId) throws IOException { String pageUrl = ""; int counter = 1; while (true) { if (counter > 10000) { break; } pageUrl = Const.huaBanPetNewPageUrl + lastPinId; String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.10 (KHTML, like Gecko) Chrome/23.0.1262.0 Safari/537.10"; String pageContent = NetUtil.getPageSourceByHTTPClient(pageUrl, "huaban.com", "http://huaban.com/", userAgent); List pins = (List) ((Map) JsonUtil.getMap4Json(pageContent)).get("pins"); if (pins.isEmpty()) { break; } for (int i = 0; i < pins.size(); i++) { Map pin = (Map) pins.get(i); String key = (String) ((Map) pin.get("file")).get("key"); key = "http://img.hb.aicdn.com/" + key; Object pinId = pin.get("pin_id"); lastPinId = pinId; System.out.println(pinId + " | " + counter + " : " + key); counter++; } } }
a02eb2bb-5113-48fe-88d4-73ec659eca65
public static void grabBeautyOldPhoto(Object lastPinId, int totalCount) throws IOException { String pageUrl = Const.huaBanBeautyOldPageUrl; for (int index = 0; index < totalCount; index++) { pageUrl = pageUrl + lastPinId; String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.10 (KHTML, like Gecko) Chrome/23.0.1262.0 Safari/537.10"; String pageContent = NetUtil.getPageSourceByHTTPClient(pageUrl, "huaban.com", "http://huaban.com/", userAgent); List pins = (List) ((Map) JsonUtil.getMap4Json(pageContent)).get("pins"); int counter = 1; for (int i = 0; i < pins.size(); i++) { Map pin = (Map) pins.get(i); String key = (String) ((Map) pin.get("file")).get("key"); key = "http://img.hb.aicdn.com/" + key; Object pinId = pin.get("pin_id"); lastPinId = pinId; System.out.println(pinId + " | " + counter + " : " + key); counter++; } } }
f6f6ccfa-262f-48a6-ab09-b3420d9ad5f7
public static void grabBeautyNewPhoto(Object lastPinId) throws IOException { String pageUrl = ""; int counter = 1; while (true) { if (counter > 10000) { break; } pageUrl = Const.huaBanBeautyNewPageUrl + lastPinId; String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.10 (KHTML, like Gecko) Chrome/23.0.1262.0 Safari/537.10"; String pageContent = NetUtil.getPageSourceByHTTPClient(pageUrl, "huaban.com", "http://huaban.com/", userAgent); List pins = (List) ((Map) JsonUtil.getMap4Json(pageContent)).get("pins"); if (pins.isEmpty()) { break; } for (int i = 0; i < pins.size(); i++) { Map pin = (Map) pins.get(i); String key = (String) ((Map) pin.get("file")).get("key"); key = "http://img.hb.aicdn.com/" + key; Object pinId = pin.get("pin_id"); lastPinId = pinId; System.out.println(pinId + " | " + counter + " : " + key); counter++; } } }
d70c9bcc-5128-4680-b62f-dfad67473aef
public void businessMethod() { }
8b1a0682-cc50-4234-9360-0ad80fc997a0
void create(NewsEntity newsEntity);
751b4160-f040-4a12-ab74-4309384b6483
void edit(NewsEntity newsEntity);
8e02b14a-0621-4311-b0fd-cd93f5e2f305
void remove(NewsEntity newsEntity);
f9ed4636-6f21-43f4-9027-8e1a20b04907
NewsEntity find(Object id);
6291bc94-fb08-4524-b7d5-8f07d5655dc4
List<NewsEntity> findAll();
27952f81-91a1-481c-ad80-1e507914872d
List<NewsEntity> findRange(int[] range);
ba177aa2-75ef-400d-98f3-e1d3cfc03826
int count();
12c50681-19d9-40a7-b7ef-006fc2b8ba6f
public NewMessage() { }
577e38ae-4c82-4855-8047-694090383dac
@Override public void onMessage(Message message) { ObjectMessage msg = null; try { if(message instanceof ObjectMessage) { msg = (ObjectMessage) message; NewsEntity e = (NewsEntity) msg.getObject(); save(e); } } catch (JMSException e) { e.printStackTrace(); mdc.setRollbackOnly(); } catch (Throwable te) { te.printStackTrace(); } }
9e68618d-82fd-413d-9866-0fd1c5893b36
private void save(Object object) { em.persist(object); }
f5393cb0-7848-48bb-9cb6-e5e4bd09b8f6
public String getTitle() { return title; }
de5cf945-3ece-4f88-b2b6-f9df5ebefbe7
public void setTitle(String title) { this.title = title; }
3542d99d-1275-49f0-989b-0b987772509e
public String getBody() { return body; }
1c46c817-6c0c-4adf-b98b-831af32a82bd
public void setBody(String body) { this.body = body; }
c7a3c1b1-baf8-4ed0-acb9-378f3379e492
public Long getId() { return id; }
782f5c2f-39f3-4b41-91b5-2545433bfb79
public void setId(Long id) { this.id = id; }
68e453e7-6069-4001-958d-b219a0c581f1
@Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; }
3f2c405e-9a30-4dad-aaa9-486f40feab48
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof NewsEntity)) { return false; } NewsEntity other = (NewsEntity) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
905fa9f8-aba1-4c25-b6da-e5e6a95a5aca
@Override public String toString() { return "ejb.NewsEntity[ id=" + id + " ]"; }
b8af9799-f9f6-410a-ab7f-2d22acd8e562
@Override protected EntityManager getEntityManager() { return em; }
684c0881-f3bb-4565-b9f3-d3ed172cf0c0
public NewsEntityFacade() { super(NewsEntity.class); }
3bcb77c4-613d-4c71-acf2-1555458ec64c
public AbstractFacade(Class<T> entityClass) { this.entityClass = entityClass; }
88464b57-a3cc-4bf2-b760-bfd44728ccda
protected abstract EntityManager getEntityManager();
1952add0-68a0-4ed3-9e94-7ec0bdeaf682
public void create(T entity) { getEntityManager().persist(entity); }
181a76e0-326b-4b9c-bac7-961ba74ec5d3
public void edit(T entity) { getEntityManager().merge(entity); }
afdb0fd7-8abd-446f-ab80-dbbbc8273911
public void remove(T entity) { getEntityManager().remove(getEntityManager().merge(entity)); }
90b583bf-7d7e-407c-baa6-ddd15de4f784
public T find(Object id) { return getEntityManager().find(entityClass, id); }
da74bb72-5e43-4d0f-9802-f8f624938d37
public List<T> findAll() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); return getEntityManager().createQuery(cq).getResultList(); }
6eef7493-21ff-47a0-a018-0613ee827cf7
public List<T> findRange(int[] range) { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); javax.persistence.Query q = getEntityManager().createQuery(cq); q.setMaxResults(range[1] - range[0] + 1); q.setFirstResult(range[0]); return q.getResultList(); }
daf808eb-7b26-4cdb-8ce7-e7352f4f4225
public int count() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); javax.persistence.criteria.Root<T> rt = cq.from(entityClass); cq.select(getEntityManager().getCriteriaBuilder().count(rt)); javax.persistence.Query q = getEntityManager().createQuery(cq); return ((Long) q.getSingleResult()).intValue(); }
875a0ef3-eee8-4ad0-8fb6-3ef3a4ae3806
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String title=request.getParameter("title"); String body=request.getParameter("body"); if ((title!=null) && (body!=null)) { try { Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(queue); ObjectMessage message = session.createObjectMessage(); // here we create NewsEntity, that will be sent in JMS message NewsEntity e = new NewsEntity(); e.setTitle(title); e.setBody(body); message.setObject(e); messageProducer.send(message); messageProducer.close(); connection.close(); response.sendRedirect("ListNews"); } catch (JMSException ex) { ex.printStackTrace(); } } try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet PostMessage</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet PostMessage at " + request.getContextPath() + "</h1>"); // The following code adds the form to the web page out.println("<form>"); out.println("Title: <input type='text' name='title'><br/>"); out.println("Message: <textarea name='body'></textarea><br/>"); out.println("<input type='submit'><br/>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } }
83c8f05e-2d30-4b2b-b075-1034ae77f7f2
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
81f37262-c3f2-40fa-a466-4fc7bbae0827
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
f67435a4-aa0d-470d-9155-c7c99495a788
@Override public String getServletInfo() { return "Short description"; }// </editor-fold>
ebfe82c4-5d17-4e8d-aa5b-04938027d781
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet ListNews</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet ListNews at " + request.getContextPath() + "</h1>"); List news = newsEntityFacade.findAll(); for(Iterator it = news.iterator(); it.hasNext();) { NewsEntity elem = (NewsEntity) it.next(); out.println(" <b>"+elem.getTitle()+"</b><br/>"); out.println(elem.getBody()+"<br />"); } out.println("<a href='PostMessage'>Add new message</a>"); out.println("</body>"); out.println("</html>"); } }
d5ab4fc3-ab02-4ea0-aa23-8b4287608be2
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
66d69e6d-6be9-4344-a184-5dba93b464dc
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
da985c00-be10-479a-b26f-33ed34a1d654
@Override public String getServletInfo() { return "Short description"; }// </editor-fold>
40b85061-f010-40d6-bdb8-f32717a0fb8d
public static void main(String[] args) {//latch的作用是牵一发而动全身,它具有的是瞬时控制效应,它不可循环利用 ExecutorService service = Executors.newCachedThreadPool(); final CountDownLatch cdOrder = new CountDownLatch(1); final CountDownLatch cdAnswer = new CountDownLatch(3); for(int i=0;i<3;i++){ Runnable runnable = new Runnable(){ public void run(){ try { Thread.sleep((long)(Math.random()*1000)); System.out.println("线程" + Thread.currentThread().getName() + "正准备接受命令"); cdOrder.await(); cdOrder.await(); cdOrder.await(); System.out.println("线程" + Thread.currentThread().getName() + "已接受命令"); cdOrder.await(); Thread.sleep((long)(Math.random()*10000)); System.out.println("线程" + Thread.currentThread().getName() + "回应命令处理结果"); cdAnswer.countDown(); } catch (Exception e) { e.printStackTrace(); } } }; service.execute(runnable); } try { Thread.sleep((long)(Math.random()*1000)); System.out.println("线程" + Thread.currentThread().getName() + "即将发布命令"); cdOrder.countDown(); System.out.println("线程" + Thread.currentThread().getName() + "已发送命令,正在等待结果"); cdAnswer.await(); System.out.println("线程" + Thread.currentThread().getName() + "已收到所有响应结果"); } catch (Exception e) { e.printStackTrace(); } service.shutdown(); }
305c787c-dea0-420e-9f36-93bc0d71bfac
public void run(){ try { Thread.sleep((long)(Math.random()*1000)); System.out.println("线程" + Thread.currentThread().getName() + "正准备接受命令"); cdOrder.await(); cdOrder.await(); cdOrder.await(); System.out.println("线程" + Thread.currentThread().getName() + "已接受命令"); cdOrder.await(); Thread.sleep((long)(Math.random()*10000)); System.out.println("线程" + Thread.currentThread().getName() + "回应命令处理结果"); cdAnswer.countDown(); } catch (Exception e) { e.printStackTrace(); } }
0cc8fd2f-339d-4e1d-b657-e5db1fb4968c
MyThread(CountDownLatch latch) { this.latch=latch; }
ab1d723e-8e3a-42bd-b828-4e65c1e658b6
public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("latch countDown..."); latch.countDown(); }
eca9090a-ec5b-4ddb-ada0-9219dca21064
public LockSummary_ABC() { condtionContext.put(Integer.valueOf(0),a); condtionContext.put(Integer.valueOf(1),b); condtionContext.put(Integer.valueOf(2),c); }
d9fcde89-8d2f-4e9f-a5c3-64d934b123db
public void print(int id) { lock.lock(); try { while (count < 30) { if (id == count%3) { if(id==0) { System.out.println(Thread.currentThread()+": "+"A"); } else if(id==1) { System.out.println(Thread.currentThread()+": "+"B"); } else { System.out.println(Thread.currentThread()+": "+"C"); } count++; Condition nextConditon = condtionContext.get(Integer.valueOf(count%3)); nextConditon.signal(); } else { Condition condition = condtionContext.get(Integer.valueOf(id)); condition.await(); } } for (Condition c : condtionContext.values()) { c.signal(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }
b8fadf42-fea3-4e05-a42f-23f5029ade3b
public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(3); final CountDownLatch latch = new CountDownLatch(1); final LockSummary_ABC printer = new LockSummary_ABC(); for (int i = 0; i < 3; i++) { final int id = i; executor.submit(new Runnable() { @Override public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } printer.print(id); } }); } System.out.println("三个任务开始顺序打印数字。。。。。。"); latch.countDown(); executor.shutdown(); }
117137b4-22d3-4a97-b322-05cc40603e46
@Override public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } printer.print(id); }
8c7af1a6-2d99-446d-ba9b-85d107aee5b8
public LockSummary_Number() { condtionContext.put(Integer.valueOf(0), c1); condtionContext.put(Integer.valueOf(1), c2); condtionContext.put(Integer.valueOf(2), c3); }
dd4daa1f-aa5d-48da-b003-78236832dbe9
public void print(int id) { lock.lock(); try { while (count * 5 < 75) { int curID = calcID();// 计算当前应该执行打印的线程 if (id == curID) { System.out.print(Thread.currentThread()+": "); for (int i = 1; i <= 5; i++) { System.out.print((count * 5 + i) + ","); } System.out.println(); count++; int nextID = calcID(); Condition nextConditon = condtionContext.get(Integer .valueOf(nextID)); // 打印完成后,通知下一个线程开始打印 nextConditon.signal(); } else { Condition condition = condtionContext.get(Integer .valueOf(id)); // 抢了打印顺序,需要等待自己的打印顺序 condition.await(); } } //完成之后,通知线程结束 for (Condition c : condtionContext.values()) { c.signal(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }
0556060e-bafc-448e-96f2-12cb1667c939
private int calcID() { return count % 3; }
6618b8eb-bcc9-4a58-b64d-d7aba61f44f3
public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(3); final CountDownLatch latch = new CountDownLatch(1); final LockSummary_Number printer = new LockSummary_Number(); for (int i = 0; i < 3; i++) { final int id = i; executor.submit(new Runnable() { @Override public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } printer.print(id); } }); } System.out.println("三个任务开始顺序打印数字。。。。。。"); latch.countDown(); executor.shutdown(); // for (int i = ) // System.out.println(); }
c1311ad7-ccd4-44bb-acfa-7d202cd0f18e
@Override public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } printer.print(id); }
81dfa980-d8a8-4a43-aa16-a046fe1e62cd
public synchronized void sub(int seq) { if (!isShouldTrue) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 1; i <= 10; i++) System.out.println("seq " + seq + " sub loop " + i); isShouldTrue = false; this.notify(); }
8c47c445-938e-437b-bb27-d803b00802b1
public synchronized void main(int seq) { if (isShouldTrue) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 1; i <= 20; i++) { System.out.println("seq " + seq + " main loop " + i); } isShouldTrue = true; this.notify(); }
c8de1464-b960-4a57-90b7-cd036c5acc2c
public static void main(String[] args) { ExecutorService service = Executors.newCachedThreadPool(); final CyclicBarrier cb = new CyclicBarrier(3,new Runnable() { public void run() { System.out.println(Thread.currentThread().getName()+"第"+count.getAndIncrement()+"个轮回"); } });//构造方法里的数字标识有几个线程到达集合地点开始进行下一步工作 for(int i=0;i<3;i++){ Runnable runnable = new Runnable(){ public void run(){ try { Thread.sleep((long)(Math.random()*10000)); System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点1,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候"); cb.await(); Thread.sleep((long)(Math.random()*10000)); System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点2,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候"); cb.await(); Thread.sleep((long)(Math.random()*10000)); System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点3,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候"); cb.await(); } catch (Exception e) { e.printStackTrace(); } } }; service.execute(runnable); } service.shutdown(); }
8c6bff9d-55f1-45d1-933b-017dd9648ad4
public void run() { System.out.println(Thread.currentThread().getName()+"第"+count.getAndIncrement()+"个轮回"); }
22b06c2e-2885-420c-a215-55536431eae4
public void run(){ try { Thread.sleep((long)(Math.random()*10000)); System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点1,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候"); cb.await(); Thread.sleep((long)(Math.random()*10000)); System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点2,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候"); cb.await(); Thread.sleep((long)(Math.random()*10000)); System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点3,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候"); cb.await(); } catch (Exception e) { e.printStackTrace(); } }
57cd424f-37c9-4726-bae1-6028c796d675
public static void main(String[] args) { Juego jueJuego = new Juego(); jueJuego.setVisible(true); jueJuego.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
1d13bee1-f899-4c0f-8b2b-925aa4db03b4
public Animacion(){ //Crea el arreglo de objetos que guarda los cuadros. cuadros = new ArrayList(); //Inicializa el tiempo total en 0. duracionTotal = 0; //Llama al método iniciar() iniciar(); }
378b80f9-e634-4b0d-b591-2824a79f533e
public synchronized void sumaCuadro(URL imagen, long duracion){ //Agrega la duración del cuadro a la duración de la animación duracionTotal += duracion; //Agrega el cuadro a la animación cuadros.add(new cuadroDeAnimacion(imagen, duracionTotal)); }
4deef2c8-1379-4874-87fe-dc3d3b46fff0
public synchronized void iniciar(){ //Inicializa el tiempo de la animación en 0 tiempoDeAnimacion = 0; //Coloca el índice en el primer cuadro de la animación indiceCuadroActual = 0; }
c56ab31c-c286-49b6-9c95-32e628e85494
public synchronized void actualiza(long tiempoTranscurrido){ //Si la animación tiene más de un cuadro, se actualiza if (cuadros.size() > 1){ //Se suma el tiempo transcurrido al tiempo total tiempoDeAnimacion += tiempoTranscurrido; /** Si el tiempo transcurrido es mayor al tiempo de la animación. */ if (tiempoDeAnimacion >= duracionTotal){ //Resetea el tiempo transcurrido tiempoDeAnimacion = tiempoDeAnimacion % duracionTotal; /** Posicional el índice en el primer cuadro */ indiceCuadroActual = 0; } /** Cuando el tiempo transcurrido es mayor al tiempo que dura el cuadro, el índice aumenta y señala al siguiente cuadro */ while (tiempoDeAnimacion > getCuadro(indiceCuadroActual).tiempoFinal){ indiceCuadroActual++; } } }
8b46726a-3cbe-433f-a05c-46dde0d6c92c
public synchronized URL getImagen(){ //Si la animación esta vacía if (cuadros.size() == 0){ //Retorna nulo return null; } //De lo contrario else { /** Llama a método getCuadro para obtener la imagen del cuadro deseado */ return getCuadro(indiceCuadroActual).imagen; } }
8ac7694b-d3ad-4ed8-a0c5-8b15d3d98eea
private cuadroDeAnimacion getCuadro(int i){ //Retorna el cuadro deseado return (cuadroDeAnimacion)cuadros.get(i); }
afb5eb2e-e406-4f71-a075-986a36b41508
public cuadroDeAnimacion(){ //Guarda valor nulo en la imagen this.imagen = null; //Guarda en 0 el tiempo this.tiempoFinal = 0; }
6e0dd90f-084d-40cd-a522-c8133d2f631f
public cuadroDeAnimacion(URL imagen, long tiempoFinal){ //Guarda la imagen del cuadro this.imagen = imagen; //Guarda el tiempo en que se da la transición al //siguiente cuadro this.tiempoFinal = tiempoFinal; }
453e95ed-d12d-4ed9-b9b3-2368977e3845
public URL getImagen(){ //Retorna la imagen return imagen; }
0cdb763f-a0d8-40fa-a71b-6c6e65382c32
public long getTiempoFinal(){ //Retorna el tiempo return tiempoFinal; }
5363e5d3-95f5-4717-96e7-622deb318f46
public void setImagen (URL imagen){ //Guarda la nueva imagen this.imagen = imagen; }
d98c76a2-0ac1-4189-9407-e60919b02dc1
public void setTiempoFinal(long tiempoFinal){ //Guarda el nuevo tiempo this.tiempoFinal = tiempoFinal; }
a17ef6da-245e-494c-a8f0-c25034027681
public SoundClip() { try { //crea el Buffer de sonido clip = AudioSystem.getClip(); } catch (LineUnavailableException e) { } }
dbe50b62-46c5-4bb4-8110-98dc99506026
public SoundClip(String filename) { //Llama al constructor default. this(); //Carga el archivo de sonido. load(filename); }
7aa2b976-e812-4c58-9fc6-8411ab2a6c49
public Clip getClip() { return clip; }
7ee448c3-e500-4925-8550-e659728e7bb8
public void setLooping(boolean looping) { this.looping = looping; }
eed6cdb8-6234-4fe3-bf1c-f5648fd71703
public boolean getLooping() { return looping; }
1bc0cb17-74ee-47e9-800b-f2b6ab660dfc
public void setRepeat(int repeat) { this.repeat = repeat; }
36348f2f-5757-47ca-88ff-ce0fc8e19698
public int getRepeat() { return repeat; }
31471b31-0b56-4269-b002-1b68e0bbfac3
public void setFilename(String filename) { this.filename = filename; }
2f5e366a-a641-4629-ae82-cab05edc703c
public String getFilename() { return filename; }
c56fff71-b1f9-4370-a365-d7deb736fd08
public boolean isLoaded() { return (boolean)(sample != null); }
69c06a63-fe83-4e46-8b6e-500868415d87
private URL getURL(String filename) { URL url = null; try { url = this.getClass().getResource(filename); } catch (Exception e) { } return url; }
a72082e2-4206-4811-9be7-8bba3bb3d0f8
public boolean load(String audiofile) { try { setFilename(audiofile); sample = AudioSystem.getAudioInputStream(getURL(filename)); clip.open(sample); return true; } catch (IOException e) { return false; } catch (UnsupportedAudioFileException e) { return false; } catch (LineUnavailableException e) { return false; } }
0b483679-606e-458c-93ec-6e81cb1b70dc
public void play() { //se sale si el sonido no a sido cargado if (!isLoaded()) return; //vuelve a empezar el sound clip clip.setFramePosition(0); //Reproduce el sonido con repeticion opcional. if (looping) clip.loop(Clip.LOOP_CONTINUOUSLY); else clip.loop(repeat); }
06d1ccb1-b540-4fd6-b5e5-d4a10db40c5c
public void stop() { clip.stop(); }
1796fa95-d41d-4849-a1d8-00f7fbcc0615
public Juego() { init(); start(); }
f8768b7a-90e2-4e62-aeda-89c9dddfaaa1
public void init() { // hago el applet de un tamaño 500,500 setSize(1200, 800); iChoque = 0; //el es cero por defecto //por defecto score empieza en 0 iScore =0; //no se ha corrido ninguna imagen de la animacion iContador = 0; //juego no esta pausado por defecto bPausa = false; //no se ha destruido ningun bloque bBloqueDestruido = false; //proyectil empieza moviendose a la derecha y arriba dirProyectilX = true; dirProyectilY = true; //la barra no se mueve al principio dirBarra = 0; //se crea sonido de impacto con bloque aucSonidoBloque = new SoundClip("wooho.wav"); //se crea sonido de impacto con suelo aucSonidoSuelo = new SoundClip("d_oh.wav"); // se crea imagen de la barra URL urlImagenBarra = this.getClass().getResource("barra.png"); // se crea la barra entBarra = new Entidad(getWidth() / 2, getHeight(), Toolkit.getDefaultToolkit().getImage(urlImagenBarra)); entBarra.setY(getHeight()-entBarra.getAlto()); entBarra.setX(getWidth()/2-entBarra.getAncho()); //velocidad de barra es 3 entBarra.setVelocidad(17); // // se obtiene las imagenes para los bloques URL urlImagenBloque = this.getClass().getResource("bloque.png"); URL urlImagenBloque2 = this.getClass().getResource("bloque2.png"); URL urlImagenBloque3 = this.getClass().getResource("bloque3.png"); URL urlImagenBloque4 = this.getClass().getResource("bloque4.png"); URL urlImagenBloque5 = this.getClass().getResource("bloque5.png"); aniBloqueDestruido = new Animacion(); aniBloqueDestruido.sumaCuadro(urlImagenBloque2, 100); aniBloqueDestruido.sumaCuadro(urlImagenBloque3, 100); aniBloqueDestruido.sumaCuadro(urlImagenBloque4, 100); aniBloqueDestruido.sumaCuadro(urlImagenBloque5, 100); // se crea el arreglo de bloques encBloques = new LinkedList(); int cantbloques = 39; int numFilas = 1; //contador de filas int numColumna = 0; //contador de columnas while(cantbloques >= 0) { cantbloques -=1; int posX = 1; int posY = 1; entBloque = new Entidad(posX,posY,Toolkit.getDefaultToolkit().getImage(urlImagenBloque)); //cada caminador tiene una velocidad al azar /* PosX y PosY dependen del tama;o del sprite, esto va a cambiar despues. */ entBloque.setX(numColumna*entBloque.getAncho()); entBloque.setY(entBloque.getAlto()*numFilas); if(numColumna >= 9) { numColumna =0; numFilas++; } else { numColumna++; } encBloques.add(entBloque); } // // se obtiene la imagen para el proyectil URL urlImagenProyectil = this.getClass().getResource("proyectil.png"); // se establece la posicion inicial, su velocidad y se crea el objeto int posX = entBarra.getX(); int posY = entBarra.getY(); entProyectil = new Entidad(posX, posY, Toolkit.getDefaultToolkit().getImage(urlImagenProyectil)); entProyectil.setY(entProyectil.getY() - entProyectil.getAlto()); entProyectil.setVelocidad(7); //se establece la posicion del proyectil //se agrega keylistener para poder detectar el teclado addKeyListener(this); }
74575bb5-6f20-45bf-9b1c-07cd531de522
public void start () { // Declaras un hilo Thread th = new Thread ((Runnable) this); // Empieza el hilo th.start (); }
49efb75b-6ae7-403d-84f0-e43358ff0d3a
public void actualiza(){ // instrucciones para actualizar Entidads //Determina el tiempo que ha transcurrido desde que el Applet //inicio su ejecución long tiempoTranscurrido=System.currentTimeMillis() - tiempoActual; //Guarda el tiempo actual tiempoActual += tiempoTranscurrido; //Actualiza la animación en base al tiempo transcurrido aniBloqueDestruido.actualiza(tiempoTranscurrido); //se cambia la posicion de la barra dependiendo del booleano 'spacebar' if (dirBarra == 1) { entBarra.setX(entBarra.getX() + entBarra.getVelocidad()); } else if(dirBarra == 2){ entBarra.setX(entBarra.getX() - entBarra.getVelocidad()); } //dirProyectilY determina si el proyectil sube o baka if (dirProyectilY) { entProyectil.setY(entProyectil.getY() + entProyectil.getVelocidad()); } else { entProyectil.setY(entProyectil.getY() - entProyectil.getVelocidad()); } //dirProyectilX determina si el proyectil se mueve la derecha o izquierda if (dirProyectilX) { entProyectil.setX(entProyectil.getX() + entProyectil.getVelocidad()); } else { entProyectil.setX(entProyectil.getX() - entProyectil.getVelocidad()); } }
e17cb41f-9a40-4d30-b9a3-023a247819e5
public void run () { // se realiza el ciclo del juego en este caso nunca termina //Guarda el tiempo actual del sistema tiempoActual = System.currentTimeMillis(); while (true) { /* mientras dure el juego, se actualizan posiciones de jugadores se checa si hubo colisiones para desaparecer jugadores o corregir movimientos y se vuelve a pintar todo */ //actualiza no se corre cuando se pausa el juego if(!bPausa) { actualiza(); } iChoque++; //se incrementa el contador checaColision(); repaint(); try { // El thread se duerme. Thread.sleep (20); } catch (InterruptedException iexError) { System.out.println("Hubo un error en el juego " + iexError.toString()); } } }
5acf74b7-2530-4841-99ef-3f998a99d2fe
public void checaColision(){ // instrucciones para checar colision y reacomodar Entidads si // es necesario //la barra no se puede salir del cuadro if(entBarra.getX()+entBarra.getAncho()>=getWidth()) { entBarra.setX(getWidth()-entBarra.getAncho()); } else if(entBarra.getY()+entBarra.getAlto()>getHeight()) { entBarra.setY(getHeight()-entBarra.getAlto()); } else if(entBarra.getX() < 0) { entBarra.setX(0); } if(entBarra.getY() < 0) { entBarra.setY(0); } //no se puede salir el proyectil //se cambia la direccion si se sale del margen if (entProyectil.getX()<=0 || entProyectil.getX() + entProyectil.getAncho() > getWidth()) { dirProyectilX = !dirProyectilX; } if (entProyectil.getY()<=0 || entProyectil.getY() + entProyectil.getAlto() > getHeight()) { dirProyectilY = !dirProyectilY; iChoque = 0; } //si Bloque choca con Nena se aumenta el score //Contador de tiempo para que no se registren dos choques al mismo tiempo for (int i = 0; i < encBloques.size(); i++) { Entidad Bloque = (Entidad)encBloques.get(i); if(entProyectil.colisiona(Bloque) && iChoque >= 3) { iChoque = 0; iScore++; //se aumenta el score //se correra la animacion en la posicion del bloque destruido aniPosX = Bloque.getX(); aniPosY = Bloque.getY(); iContador = 0; encBloques.remove(Bloque); if(entProyectil.getY()<=entBloque.getY()+entBloque.getAlto() || entProyectil.getY() + entProyectil.getAlto() >= Bloque.getY()) { dirProyectilY = !dirProyectilY; } else { dirProyectilX = !dirProyectilX; } //encBloques.remove(Bloque); //se elimina el bloque con el que se colisiono aucSonidoBloque.play(); //emite sonido } } if(entBarra.colisiona(entProyectil) && iChoque >= 10) { iChoque = 0; if( entProyectil.getY() + entProyectil.getAlto() >= entBarra.getY()) { dirProyectilY = !dirProyectilY; } else { dirProyectilX = !dirProyectilX; } } }