62,623
社区成员
发帖
与我相关
我的任务
分享package Threads;
public class AddThread implements Runnable{
private volatile static int sum = 0;
public AddThread(){
}
public void run(){
{
for(int i = 0;i<10;++i){
int temp = sum;
temp = temp +1;
try{
Thread.sleep(20);
}catch(InterruptedException e){
System.out.println(e);
}
sum = temp;
System.out.println("This sum is "+ sum);
}
}
}
public static int getSum(){
return sum;
}
}
package Threads;
public class Core {
public static void main(String[] args){
AddThread first = new AddThread();
AddThread second = new AddThread();
Thread one = new Thread(first);
Thread two = new Thread(second);
one.setName("firstThread");
two.setName("secondThread");
one.start();
two.start();
while(one.isAlive()||two.isAlive()){
}
System.out.println(AddThread.getSum());
}
}
final AtomicInteger sum=new AtomicInteger(0);
for(int i=0;i<2;i++)
new Thread(){
public void run(){
for(int i=0;i<10;++i){
try{
Thread.sleep(20);
}catch(InterruptedException e){
}
System.out.println("This sum is "+sum.addAndGet(1));
}
}
}.start();
public class AddThread implements Runnable{
private static int sum=0;
public AddThread(){
}
private synchronized static void add(){
sum++;
}
public void run(){
for(int i = 0;i<10;++i){
add();
System.out.println("This sum is "+ sum);
}
}
public static int getSum(){
return sum;
}
}
int temp = sum;
temp = temp +1;
try{
Thread.sleep(20);
}catch(InterruptedException e){
System.out.println(e);
}
sum = temp;