1.2.4打印方法与变量i--的问题

来源:互联网 发布:为什么黑客都用python 编辑:程序博客网 时间:2024/06/05 15:53

package demo;/** * Created by sunyifeng on 17/10/9. */public class MyThread extends Thread {    private int i = 5;    @Override    public void run() {        System.out.println("i=" + (i--) + ",threadName=" + Thread.currentThread().getName());    }}
package demo;/** * Created by sunyifeng on 17/10/9. */public class Run {    public static void main(String[] args) {        MyThread run = new MyThread();        Thread thread1 = new Thread(run);        Thread thread2 = new Thread(run);        Thread thread3 = new Thread(run);        Thread thread4 = new Thread(run);        Thread thread5 = new Thread(run);        //        thread1.start();        thread2.start();        thread3.start();        thread4.start();        thread5.start();    }}
运行结果:

i=4,threadName=Thread-2
i=3,threadName=Thread-3
i=2,threadName=Thread-4
i=5,threadName=Thread-1
i=1,threadName=Thread-5

程序说明:

1、打印结果出现非线程安全问题;

2、println()方法是线程安全的(见源码),但以上的run方法非线程安全。

原创粉丝点击