标签:style blog ar color 使用 sp for java strong
题目要求:对象完成,这样就可以实现对该数据处理的互斥与通信。
class ShareData { private int x = 0; public synchronized void addx(){ x++; System.out.println("x++ : "+x); } public synchronized void subx(){ x--; System.out.println("x-- : "+x); } } class MyRunnable1 implements Runnable{ private ShareData share1 = null; public MyRunnable1(ShareData share1) { this.share1 = share1; } public void run() { for(int i = 0;i<100;i++){ share1.addx(); } } } class MyRunnable2 implements Runnable{ private ShareData share2 = null; public MyRunnable2(ShareData share2) { this.share2 = share2; } public void run() { for(int i = 0;i<100;i++){ share2.subx(); } } } public class ThreadsVisitData { public static void main(String[] args) { ShareData share = new ShareData(); new Thread(new MyRunnable1(share)).start(); new Thread(new MyRunnable2(share)).start(); } }
第二种:
将这些Runnable对象作为某一个类的内部类,共享的数据作为外部类的成员变量,对共享数据的操作分配给外部类的方法来完成,以此实现对操作共享
数据的互斥和通信,作为内部类的Runnable来操作外部类的方法,实现对数据的操作
class ShareData { private int x = 0; public synchronized void addx(){ x++; System.out.println("x++ : "+x); } public synchronized void subx(){ x--; System.out.println("x-- : "+x); } } public class ThreadsVisitData { public static ShareData share = new ShareData(); public static void main(String[] args) { //final ShareData share = new ShareData(); new Thread(new Runnable() { public void run() { for(int i = 0;i<100;i++){ share.addx(); } } }).start(); new Thread(new Runnable() { public void run() { for(int i = 0;i<100;i++){ share.subx(); } } }).start(); } }
标签:style blog ar color 使用 sp for java strong
原文地址:http://blog.csdn.net/wjw0130/article/details/41857287