模拟线程安全问题

来源:互联网 发布:mac 如何打开终端 编辑:程序博客网 时间:2024/05/17 01:48

package com.xiaozhi.threads;/* * Runnable避免了单继承的缺陷 * Runable里面的变量共享 */public class Test3 {public static void main(String[] args) {RunTicket runTicket=new RunTicket();Thread thread1=new Thread(runTicket);Thread thread2=new Thread(runTicket);Thread thread3=new Thread(runTicket);Thread thread4=new Thread(runTicket);thread1.start();thread2.start();thread3.start();thread4.start();}}class RunTicket implements Runnable{private int num=100;@Overridepublic void run() {while(true){if(num>0){try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+"---------"+--num);}}}}

原创粉丝点击