62,628
社区成员
发帖
与我相关
我的任务
分享
public class Test {
public static void main(String[] args) {
MyThreads t=new MyThreads();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class MyThreads implements Runnable{
int tk=10;
public void run(){
for(;tk>0;tk--){
System.out.println(Thread.currentThread().getName()+" "+tk);
}
}
}
但是如果将run中的内容改一下
while(tk>0){
System.out.println(Thread.currentThread().getName()+" "+tk--);//重点是在这里让tk自减
}
while(tk>0){ //no happens-before
int curVal = tk; //no happens-before
synchronized (this) { //happens-before bolck
tk--;
System.out.println(Thread.currentThread().getName()+" "+ curVal);//重点是在这里让tk自减
}
}
可以解决while(tk>0)不生效问题但不能解决重复的问题。
while(tk>0){ //no happens-before
synchronized (this) { //happens-before bolck
int curVal = tk;
tk--;
System.out.println(Thread.currentThread().getName()+" "+ curVal);//重点是在这里让tk自减
}
}
可以解决重复问题,但不能解决while(tk>0)的问题
while(true){
synchronized (this) { //happens-before block
int curVal = tk;
if(curVal == 0){
break;
}
tk--;
System.out.println(Thread.currentThread().getName()+" "+ curVal);//重点是在这里让tk自减
}
}
可以解决所有问题
class MyThreads implements Runnable{
int tk=10;
public void run(){
for(;tk>0;tk--){
System.out.println(Thread.currentThread().getName()+" "+tk);
}
}
}
while (tk > 0) {
System.out.println(Thread.currentThread().getName() + " " + tk);
tk--;
}
while(tk>0){
System.out.println(Thread.currentThread().getName()+" "+tk--);//重点是在这里让tk自减
}
while(tk>0){
int curVal = tk;
tk--;
System.out.println(Thread.currentThread().getName()+" "+ curVal);//重点是在这里让tk自减
}
static class MyThreads implements Runnable {
int tk = 10;
public void run() {
for (; tk > 0; tk--) {
a(tk);
}
}
public void a(int val){
}
}
public void run();
Code:
0: goto 21
3: aload_0
4: aload_0
5: getfield #14; //Field tk:I
8: invokevirtual #21; //Method a:(I)V
11: aload_0
12: dup
13: getfield #14; //Field tk:I
16: iconst_1
17: isub
18: putfield #14; //Field tk:I
21: aload_0
22: getfield #14; //Field tk:I
25: ifgt 3
28: return