
正文
多线程java测试代码 多线程java测试代码怎么写
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
Java 多线程和单线程效率比较,最好是能上代码,我使用了多线程发现耗时更多,求大神解释!
单线程比多线程更快。你的测试代码只是用了CPU资源。因为多线程需要处理线程的开销,开销多了自然没有单线程快。
多线程是为了更充分的利用计算机的资源。比如网络,IO,CPU...如果你在for循环里加入一个磁盘写入操作,多线程就会比单线程快了
相关问答
Q1: java多线程编程代码如下,输出结果如下:
首先,你同步多线程java测试代码的是具体的某个Test实例, 对于那个实例来说,实际上只有一个线程访问了那个代码块,但是sum和other却是多个线程同时去进行访问,实际上这是不安全的,如果你想实现每次都输出10000的效果,那么正确的应该是在Test.class上加锁,而不是获取Test实例的锁,修改后的代码如下多线程java测试代码:
public class Test extends Thread {
public static int sum = 10000;
public static int other = 0;
public void getMoney() {
synchronized (Test.class) {
System.out.println(Thread.currentThread().getName() + " 开始执行");
sum = sum - 100;
System.out.println("sum-100");
other = other + 100;
System.out.println("other+100");
System.out.println(sum + other);
System.out.println(Thread.currentThread().getName() + " 执行完成");
}
}
public void run() {
getMoney();
}
public static void main(String[] agrs) {
Thread t[] = new Thread[10];
for (int i = 0; i = 9; i++) {
t[i] = new Test();
t[i].start();
}
}
}
// 上面代码能得到你的结果
Q2: java线程的经典代码
package threadgroup;
class ThreadDemo3 extends Thread {
private String name;
private int delay;
public ThreadDemo3(String sname, int i_delay) {
name = sname;
delay = i_delay;
}
public void run() {
try {
sleep(delay);
} catch (InterruptedException e) {
}
System.out.println("多线程测试!\n" + name + "\n" + delay);
}
}
public class testMyThread {
public static void main(String[] args) {
ThreadDemo3 th1,th2,th3;
th1 = new ThreadDemo3("线程1", (int) (Math.random() * 900));
th2 = new ThreadDemo3("线程2", (int) (Math.random() * 900));
th3 = new ThreadDemo3("线程3", (int) (Math.random() * 900));
th1.start();
th2.start();
th3.start();
}
}
package threadgroup;
public class threadDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
t.setName("你好吗?");
System.out.println("正在进行的Thread是:" + t);
try {
for (int i = 0; i 5; i++) {
System.out.println("我不叫穆继超" + i);
Thread.sleep(3000);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());
}
}
}
package threadgroup;
public class threadDemo2 implements Runnable {
public threadDemo2() {
Thread t1 = Thread.currentThread();
t1.setName("第一个主进程");
System.out.println("正在运行" + t1);
Thread t2 = new Thread(this, "");
System.out.println("在创建一个进程");
t2.start();
try {
System.out.println("使他进入第一个睡眠状态");
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread has wrong" + e.getMessage());
}
System.out.println("退出第一个进程");
}
public void run() {
try {
for (int i = 0; i 5; i++) {
System.out.println("进程" + i);
Thread.sleep(3000);
}
} catch (InterruptedException e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());
}
System.out.println("退出第二个进程");
}
public static void main(String[] args) {
new threadDemo2();
}
}
多线程java测试代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于多线程java测试代码怎么写、多线程java测试代码的信息别忘了在本站进行查找喔。







