多线程间的通信问题之交替打印

1.要实现的效果,直接上图:

1.具体逻辑很清晰,就是通过多线程来实现直接上代码,,lock控制相同的输入或输出线程的同步,resource控制着输入和输出线程的同步

class Resource{private String name;private String sex;private boolean flag;public void setName(String name){this.name=name;}public void setSex(String sex){this.sex=sex;}public void setFlag(boolean flag){this.flag=flag;}public String getName(){return this.name;}public String getSex(){return this.sex;}public boolean getFlag(){return this.flag;}}class Input implements Runnable{private static final Object lock=new Object();int num=0;Resource resource;public Input(Resource resource){this.resource=resource;}@Overridepublic void run() {// TODO Auto-generated method stubwhile (!Thread.interrupted()) {//调用interrupt方法时终止线程synchronized (lock) {synchronized (resource) {if(resource.getFlag()){try {resource.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if((num&1)==0)//用奇数偶数来实现交替输出{resource.setSex("male");resource.setName("mnmlist");}else{resource.setSex("female");resource.setName("sting");}num++;if(num>10000)Thread.currentThread().interrupt();resource.setFlag(true);resource.notify();}}}}}class Output implements Runnable{private static final Object lock=new Object();int num=0;Resource resource;public Output(Resource resource){this.resource=resource;}@Overridepublic void run() {// TODO Auto-generated method stubwhile (!Thread.interrupted()) {synchronized (lock) {synchronized (resource) {if(!resource.getFlag()){try {resource.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}System.out.println(Thread.currentThread().getName()+","+(++num)+"th,姓名:"+resource.getName()+",性别:"+resource.getSex());if(num>10000)Thread.currentThread().interrupt();resource.setFlag(false);resource.notify();}}}}}public class OneAfterAnotherOutput {public static void main(String[] args) {// TODO Auto-generated method stubResource resource=new Resource();Input input=new Input(resource);Output output=new Output(resource);Input input1=new Input(resource);Output output1=new Output(resource);Thread inputThread=new Thread(input);Thread outputThread=new Thread(output);Thread inputThread1=new Thread(input1);Thread outputThread1=new Thread(output1);inputThread.start();outputThread.start();inputThread1.start();outputThread1.start();}}

即使是不成熟的尝试,也胜于胎死腹中的策略。

多线程间的通信问题之交替打印

相关文章:

你感兴趣的文章:

标签云: