//我期望的结果是:
//分别加减到多少随便线程自己。
//线程1:0 1 2 3 4 5
//线程2:4 3 2 1 0 -1 -2
//线程1:-1 0 1 2 3 ...
//...
public class ThreadPlusAndMinus { private int count;
private int isRun;
public static void main(String[] args) { ThreadPlusAndMinus tpm = new ThreadPlusAndMinus();
Thread t1 = new Thread(tpm.new MyThread(true));
// Thread t2 = new Thread(tpm.new MyThread(true));
// Thread t3 = new Thread(tpm.new MyThread(false));
Thread t4 = new Thread(tpm.new MyThread(false));
t1.start();
// t2.start();
// t3.start();
t4.start();
} private class MyThread implements Runnable { private boolean isPlus; public MyThread(boolean isPlus) {
this.isPlus = isPlus;
} @Override
public synchronized void run() {
while (isRun++ < 100) {
if (isPlus)
count++;
else
count--;
System.out.println(Thread.currentThread().getName() + ":" + count);
}
}
}
}
//分别加减到多少随便线程自己。
//线程1:0 1 2 3 4 5
//线程2:4 3 2 1 0 -1 -2
//线程1:-1 0 1 2 3 ...
//...
public class ThreadPlusAndMinus { private int count;
private int isRun;
public static void main(String[] args) { ThreadPlusAndMinus tpm = new ThreadPlusAndMinus();
Thread t1 = new Thread(tpm.new MyThread(true));
// Thread t2 = new Thread(tpm.new MyThread(true));
// Thread t3 = new Thread(tpm.new MyThread(false));
Thread t4 = new Thread(tpm.new MyThread(false));
t1.start();
// t2.start();
// t3.start();
t4.start();
} private class MyThread implements Runnable { private boolean isPlus; public MyThread(boolean isPlus) {
this.isPlus = isPlus;
} @Override
public synchronized void run() {
while (isRun++ < 100) {
if (isPlus)
count++;
else
count--;
System.out.println(Thread.currentThread().getName() + ":" + count);
}
}
}
}
解决方案 »
- 一个有趣的算法题。各位能不能给点思路。有代码更好,最好是java的代码。谢谢!
- java UDP 网路编程 接收不到数据??请大家帮帮忙
- 寻找csdn里的java高手
- 不要不好意思,大家来聊聊====〉socket通信到底是根据那个协议TCP还是udp.顺便问下java下如何实现Telnet
- 很菜的问题,可我就是不会
- java 按下回车跳转到下一个TextField
- Java变量的访问方法???
- 一个基本语法问题,帮帮忙!!!!!!看看和C++有什么不同?
- JB4 foundcation for Linux不能安装?
- 脱产三个月冲击SCJP,行吗?
- 用动态规划的方法求最长路径(在线等)
- 急,ArrayList类型报错
MyThread mt = new MyThread(true);
Thread t1 = new Thread(mt);
Thread t2 = new Thread(mt);
改成上面这样t1,t2两个线程才有共享的资源即临界资源(具体到这里就是mt),才有做同步的必要