6核心类8多线程.ppt

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
6核心类

class ThreadDemo1 { public static void main(String arg[]) { tt.setDaemon(true); TestThread tt=new TestThread(); tt.start(); } } class TestThread extends Thread { public void run() { while(true){System.out.println(run(): +Thread.currentThread().getName());} } } 这个运行无任何输出。 * class yourThread extends Thread { Guard m; public yourThread(Guard my) { m=my; } public void run() { for(int i=0;i10;i++) { m.setValue(); try{ this.sleep(1000); }catch(Exception e) { System.out.println(e.toString()); } } } } class myThread extends Thread {Guard m; public myThread(Guard my) { m=my;} public void run() { for(int i=0;i10;i++) { System.out.println(get value is : +m.getValue()); try{ this.sleep(1000);} catch(Exception e) { System.out.println(e.toString()); } } } } * public class synchronizedtest { public static void main(String arg[]) { Guard g=new Guard(); myThread my1=new myThread(g); yourThread your=new yourThread(g); my1.start(); your.start(); } } * 同步方法 Synchronized void get() {………………………..} 同步语句块 void get() { ……….. ………. synchronized (this) {……………} } * Synchronization(同步) Mutual exclusion(互斥) Thread Communication (线程间通信) or coordination (协作) * 8.3.2 同步(Synchronization) ------线程通信或协作 [同步的目的之一是保持共享资源的一致性,同时它也可以使线程之间实现协作] Show 【线程之间的协作,可以通过继承自Object类的wait ,nofity方法来实现】 * Example 生产者/消费者 * class SyncStack{ //同步堆栈类 private int index = 0; //堆栈指针初始值为0 private String[] buffer=new String[6]; public synchronized void push(String c){ //加上互斥锁 while(index ==buffer.length){ //堆栈已满,不能压栈 try{this.wait(); //等待,直到有数据出栈 }catch(InterruptedException e){} } this.notify();//通知其它线程把数据出栈 buffer[index] = c; //数据入栈 index++; //指针向上移动 System.out.println(in :producer +c); } public synchronized String pop(){ //加上互斥锁 while(index ==0){ //堆栈无数据,不能出栈 try{this.wait(); //等待其它线程把数据入栈 }catch(InterruptedException e){} } this.notify(); //通知其它线程入栈 index--; //指针向下移动 System.out.println(out: consumer+ buffer[index]); ret

文档评论(0)

sd44055 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档