package main.finals;
public class ThreadShareDataTest {
/**
* @param args
*/
private static ShareDatas shareDate = new ShareDatas();
public static void main(String[] args) {
// 实现方法一
for (int i = 0; i < 2; i++) {//定义两组相加相间的操作
new Thread(new Runnable() {//对j进行加操作
public void run() {
shareDate.inc();
}
}).start();
new Thread(new Runnable() {
public void run() {//对j进行减操作
shareDate.dec();
}
}).start();
}
// 实现方法二
for(int i=0;i<2;i++){
new Thread(new MyThread1(shareDate)).start();
new Thread(new MyThread2(shareDate)).start();
}
}
}
class ShareDatas {
private int j;
public synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName()
+ "(increase thread): j=" + j);
}
public synchronized void dec() {
j--;
System.out.println(Thread.currentThread().getName()
+ "(decrease thread): j=" + j);
}
}
class MyThread1 implements Runnable{
private ShareDatas shareDatas;
public MyThread1(ShareDatas shareDatas){
this.shareDatas=shareDatas;
}
@Override
public void run() {
// TODO Auto-generated method stub
shareDatas.inc();
}
}
class MyThread2 implements Runnable{
private ShareDatas shareDatas;
public MyThread2(ShareDatas shareDatas){
this.shareDatas=shareDatas;
}
@Override
public void run() {
// TODO Auto-generated method stub
shareDatas.dec();
}
}
java经典面试题-2个线程同时对j加,2个线程同时对就减
最新推荐文章于 2024-08-15 14:47:41 发布