Java之Thread(线程题)

特别说明:java线程相关的参考了张孝祥老师的代码
参考资料:
《深入浅出 Java Concurrency》目录
http://www.blogjava.net/xylz/archive/2010/07/08/325587.html
问题如下:
设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1!
public class MultiThreadTest {

	
	static MyData m = new MyData();
	
	public static void main(String[] args) {
		
		MyData m2 = new MyData();
		new Thread(new MyDataManager(m2)).start();
		new Thread(new MyDataManager2(m2)).start();		
		
		
		new Thread(new Runnable(){
			@Override
			public void run() {
				m.inc();
								
			}
		}).start();
		
		new Thread(new Runnable(){
			@Override
			public void run() {
				m.dec();
								
			}
		}).start();
		
		System.out.println(m.getAge());

	}

}

class MyDataManager implements Runnable{
	MyData m ;
	public MyDataManager(MyData m){
		this.m = m;
	}
	@Override
	public void run() {
		m.inc();		
	}
}
class MyDataManager2 implements Runnable{
	MyData m ;
	public MyDataManager2(MyData m){
		this.m = m;
	}
	@Override
	public void run() {
		m.dec();	
	}
}

class MyData{
	private int age = 0;
    synchronized void inc(){
		++age;
	}
    synchronized void dec(){
		--age;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}	
}

网上实现如下:
http://skyuck.iteye.com/blog/540660
public class threadtest1 {
  private int j;
  Thread thread = new Thread();
  private synchronized void inc() {
  j++;
  System.out.println(thread.currentThread().getName() + "-inc:" + j);
  }

  private synchronized void dec() {
  j--;
  System.out.println(thread.currentThread().getName() + "-dec:" + j);
  }

  class inc implements Runnable {
  public void run() {
  for (int i = 0; i < 100; i++) {
  inc();
  }
  }
  }

  class dec implements Runnable {
  public void run() {
  for (int i = 0; i < 100; i++) {
  dec();
  }
  }
  }

  public static void main(String[] args) {
  threadtest1 tt = new threadtest1();
  inc inc = tt.new inc();
  dec dec = tt.new dec();
  for (int i = 0; i < 2; i++) {
  Thread t = new Thread(inc);
  t.start();
  t = new Thread(dec);
  t.start();
  }
  }
}

你可能感兴趣的:(java,thread)