标签:java
public class Data { String name = "林俊杰"; //初始化数据 String sex="男"; boolean isNull=false; //标识 public synchronized void put(String name,String sex) //存入数据方法 { if(isNull) //当数据类不为空时获得该旗标的线程进入等待状态 try {wait();} catch (InterruptedException e1) {e1.printStackTrace();} this.name=name; try{Thread.sleep(100);}catch(Exception e){e.printStackTrace();} this.sex=sex; isNull=true; notify(); } public synchronized void get() //读取数据方法 { if(!isNull)//当数据还没有被写入完成时获取该旗标的线程进入等待状态 try {wait();} catch (InterruptedException e1) {e1.printStackTrace();} System.out.println(name+" : "+sex); isNull=false; notify(); } }
public class Producer implements Runnable { Data data=null; public Producer(Data data) //构造方法 { this.data=data; } public void run() { int i=0; while(true) { if(i==0) { data.put("吴倩","女"); } else { data.put("林俊杰","男"); } i=(i+1)%2; } } }
class Customer implements Runnable { Data data=null; public Customer(Data data) { this.data=data; } public void run() { while(true) { data.get(); } } }
public class ThreadCommunication { public static void main(String[] args) { Data data = new Data(); new Thread(new Producer(data)).start(); //生产者线程 new Thread(new Customer(data)).start();//消费者线程 } }
public class threadRunnable implements Runnable { boolean stopFlag=true; //定义一个标识 //停止线程方法 public void stopMe() { stopFlag=false; } //run方法 public void run() { while(stopFlag) { System.out.println(Thread.currentThread().getName()+" is running"); } } }
public class ThreadLife { public static void main(String[] args) { threadRunnable runnable = new threadRunnable(); new Thread(runnable).start(); for(int i=0;i<100;i++) { if(i==50) //当i累加到50时,结束子线程 { runnable.stopMe(); } System.out.println("MainThread is running"); } } }
标签:java
原文地址:http://blog.csdn.net/u012637501/article/details/43125451