线程锁定

来源:互联网 发布:mysql delete join 编辑:程序博客网 时间:2024/05/05 22:18
 

import java.awt.*;
import java.util.Date;

import javax.swing.*;
public class Test implements Runnable {
        private Timer  timer = new Timer();
 public static void main(String[]args){
      Test test = new Test();
      Thread myThread1 = new Thread(test);
      Thread myThread2 = new Thread(test);
      myThread1.setName("myThread1");
      myThread2.setName("myThread2");
      myThread1.start();
      myThread2.start();
 }

 @Override
 public void run() {
  timer.add(Thread.currentThread().getName());// 获取当前线程;
 }
}
class Timer {
 private static int num = 0;
 public synchronized void  add(String name){//synchronized 互斥锁,执行这个方法的过程中,当前对象被锁定
  num++;//synchronized(this){
  try {
   Thread.sleep(1000);
  }catch(InterruptedException e){}
  System.out.println(name+"你是第"+num+"个线程");
 //}
 }
}
/*
  synchronized 能锁定某一段代码,执行这段代码的过程中,当前对象被锁定,其他对象必须等待其完成。。
输出:   myThread1你是第1个线程
          myThread2你是第2个线程
若无synchronized 锁定: myThread1你是第2个线程
                        myThread2你是第2个线程
 
*/

原创粉丝点击