多线程不访问同一全局变量会怎么样?内详
就是假如开启三个线程,他们直接没有相同的变量要访问,就是假如线程A访问变量a,线程B访问变量b,线程C访问变量c,这样做有意义吗,会不会提升速度?...
就是假如开启三个线程,他们直接没有相同的变量要访问,就是假如线程A访问变量a,线程B访问变量b,线程C访问变量c,这样做有意义吗,会不会提升速度?
展开
1个回答
展开全部
是否用线程,要看你是否需要!如果你有需要并发处理的任务,可以开线程,如果像你说的这样,没有数据同步的需要,根据我做的测试的结果,反而会降低速度。
先单独运行,然后运行test
(下面代码的测试结果部分取决于机器本身)
下面附上我的测试代码:
ThreadA
public class ThreadA implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
long startTime = System.currentTimeMillis();
long number = 0L;
for(int index = 0; index < Integer.MAX_VALUE; index++){
number += index;
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void main(String[] args) {
ThreadA a = new ThreadA();
a.run();
}
}
ThreadB
public class ThreadB implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
long startTime = System.currentTimeMillis();
long number = 0L;
for(int index = 0; index < Integer.MAX_VALUE; index++){
number += index;
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.run();
}
}
Test
public class Test {
public static void main(String[] args) {
Thread a = new Thread(new ThreadA());
Thread b = new Thread(new ThreadB());
a.start();
b.start();
}
}
先单独运行,然后运行test
(下面代码的测试结果部分取决于机器本身)
下面附上我的测试代码:
ThreadA
public class ThreadA implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
long startTime = System.currentTimeMillis();
long number = 0L;
for(int index = 0; index < Integer.MAX_VALUE; index++){
number += index;
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void main(String[] args) {
ThreadA a = new ThreadA();
a.run();
}
}
ThreadB
public class ThreadB implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
long startTime = System.currentTimeMillis();
long number = 0L;
for(int index = 0; index < Integer.MAX_VALUE; index++){
number += index;
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.run();
}
}
Test
public class Test {
public static void main(String[] args) {
Thread a = new Thread(new ThreadA());
Thread b = new Thread(new ThreadB());
a.start();
b.start();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询