您的位置:首页 > 其它

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

2017-10-09 22:43 92 查看
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方法非线程安全。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: