版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/windzzm/article/details/73282385
1、线程不共享数据
对同一资源,各个线程各自执行一遍,代码如下:
package com.zzm.th01;
/**
* 线程不共享数据
* Created by ming on 2017/6/15.
*/
public class th04 extends Thread{
//记录资源总数
private int count = 4;
@Override
public void run() {
super.run();
count--;
System.out.println(Thread.currentThread().getName()+"执行->"+count);
}
public static void main(String[] args) {
th04 th = new th04();
th04 th1 = new th04();
th04 th2 = new th04();
th.start();
th1.start();
th2.start();
}
}
2、线程数据共享
这种情况会有非线程安全问题。需要加synchronized。代码如下:
package com.zzm.th01;
/**
* Created by ming on 2017/6/15.
*/
public class th05 extends Thread {
int count = 7;
@Override
synchronized public void run() {
super.run();
count--;
System.out.println(Thread.currentThread().getName()+"执行->"+count);
}
public static void main(String[] args) {
th05 th = new th05();
Thread th1 = new Thread(th,"线程1");
Thread th2 = new Thread(th,"线程2");
Thread th3 = new Thread(th,"线程3");
th1.start();
th2.start();
th3.start();
}
}