ThreadTest.java:
[java] view plain copy print ? [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m1NT9ROO-1637393286630)(https://code.csdn.net/assets/CODE_ico.png)] [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pZVpNmkd-1637393286638)(https://code.csdn.net/assets/ico_fork.svg)]
public class ThreadTest {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
Count count = new Count();
public void run() {
count.count();
}
};
for(int i = 0; i < 10; i++) {
new Thread(runnable).start();
}
}
}
这里启动了10个线程,看一下输出结果:
[java] view plain copy print ? [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OMtiSXjk-1637393286639)(https://code.csdn.net/assets/CODE_ico.png)] [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6wuOQEjJ-1637393286640)(https://code.csdn.net/assets/ico_fork.svg)]
Thread-0-55
Thread-1-110
Thread-2-165
Thread-4-220
Thread-5-275
Thread-6-330
Thread-3-385
Thread-7-440
Thread-8-495
Thread-9-550
只有Thread-0线程输出的结果是我们期望的,而输出的是每次都累加的,这里累加的原因以后的博文会说明,那么要想得到我们期望的结果,有几种解决方案:
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》 浏览器打开:qq.cn.hn/FTe 开源分享
;
[java] view plain copy print ? [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hJ6e3W6B-1637393286641)(https://code.csdn.net/assets/CODE_ico.png)] [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TyQQGGdY-1637393286642)(https://code.csdn.net/assets/ico_fork.svg)]
public class Count {
public void count() {
int num = 0;
for(int i = 1; i <= 10; i++) {
num += i;
}
System.out.println(Thread.currentThread().getName() + “-” + num);
}
}
将线程类成员变量拿到run方法中,这时count引用是线程内的局部变量;
[java] view plain copy print ? [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-w4X2qimR-1637393286642)(https://code.csdn.net/assets/CODE_ico.png)] [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RH7Phgay-1637393286643)(https://code.csdn.net/assets/ico_fork.svg)]
public class ThreadTest4 {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
Count count = new Count();
count.count();
public void run() {
Count count = new Count();
count.count();