java用20个线程,对一个int进行操作,10个负责加,10个负责减。一次只加1或减1,进行100次。如何保证线程安全的同时,使运行效率比单线程要高呢?
新手,硬生生把每次加减操作都加了锁。运行比单线程慢得多。老大又要求我写个多线程的出来。以下代码老大是说我没理解多线程,运行效率慢。请问可以怎么改呢?求大神指点
public class PlusThread implements Runnable{
private MyThread thread;
public PlusThread(MyThread thread){
this.thread=thread;
}
@Override
public void run() {
// TODO Auto-generated method stub
thread.plus();
}
}
public class SubtractThread implements Runnable{
private MyThread thread;
public SubtractThread(MyThread thread){
this.thread=thread;
}
@Override
public void run() {
// TODO Auto-generated method stub
thread.subtract();
}
}
public class MyThread{
private static int number=100;
public static void main(String[] args) throws InterruptedException{
// TODO Auto-generated method stub
MyThread thread=new MyThread();
PlusThread plusTh=new PlusThread(thread);
SubtractThread subtractTh=new SubtractThread(thread);
for(int i=0;i<10;i++){
new Thread(plusTh).start();;
new Thread(subtractTh).start();
}
Thread.sleep(400);
System.out.println(number);
}
public void plus(){
synchronized(MyThread.class){
for(int i=0;i<100;i++){
number++;
}
}
System.out.println(Thread.currentThread().getName()+" : "+number);
}
public void subtract(){
synchronized(MyThread.class){
for(int i=0;i<100;i++){
number--;
}
}
System.out.println(Thread.currentThread().getName()+" : "+number);
}
}