- public class threadAndRunnable {
- public static void main(String[] args) {
- ticket tic=new ticket(); //创建线程对象
-
- Thread t1=new Thread(tic);
- Thread t2=new Thread(tic);
- Thread t3=new Thread(tic);
-
- t1.start(); //启动线程
- t2.start();
- t3.start();
- }
- }
- //实现接口创建线程
- class ticket implements Runnable //extends Thread
- {
- private int tic=200;
- @Override
- public void run() { //重写Run方法
- while(true){
- synchronized (new Object()) { //给线程上锁
- if(tic>0){
- try {
- Thread.sleep(10); //线程冻结状态
- System.out.println(Thread.currentThread().getName()+"---tic:"+tic--);
- } catch (InterruptedException e) {
- e.toString();
- }
- }
- }
- }
- }
-
- }
复制代码 给线程加了锁,但还是出现0或负值的情况,怎么回事?!!
|
|