/**
* User: ldj
* Date: 2023/5/18
* Time: 18:04
* Description: 线程变量共享测试
*/
public class MultiTheadDemo {
public static void main(String[] args) {
int count = 10;
{
new ExtendThread("a", count).start();//9
new ExtendThread("b", count).start();//9
new ExtendThread("c", count).start();//9
}
{
//CustomRunnable封装了变量count,对象可以被线程多次访问
CustomRunnable customRunnable = new CustomRunnable(count);
new Thread(customRunnable, "d").start();
new Thread(customRunnable, "e").start();
new Thread(customRunnable, "f").start();
//变量count都是封装在CustomRunnable,每次new CustomRunnable count==10
//new Thread(new CustomRunnable(count), "d").start();//9
//new Thread(new CustomRunnable(count), "e").start();//9
//new Thread(new CustomRunnable(count), "f").start();//9
//System.out.println("local:" + count);//10
}
}
}
//不可以共享变量count
class ExtendThread extends Thread {
private int count;
public ExtendThread(String name, int count) {
super(name);
this.count = count;
}
@Override
public void run() {
count = count - 1;
System.out.println(Thread.currentThread().getName() + "::" + count);
}
}
//可以共享变量count
class CustomRunnable implements Runnable {
private int count;
public CustomRunnable(int count) {
this.count = count;
}
@Override
public void run() {
count = count - 1;
System.out.println(Thread.currentThread().getName() + "::" + count);
}
}
多线程变量共享
最新推荐文章于 2024-07-24 19:13:29 发布