代码
package com.vista; class MyThread implements java.lang.Runnable { private int threadId; private static Object lock = new Object(); public MyThread(int id) { this.threadId = id; }
@Override public void run() { synchronized (lock) { for (int i = 0; i < 100; ++i) { System.out.println("Thread ID: " + this.threadId + " : " + i); } } } }
public class ThreadDemo { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 10; ++i) { new Thread(new MyThread(i)).start(); Thread.sleep(1); } } } |
再来看第一段代码,实例方法中加入sychronized关键字封锁的是this对象本身,而在静态方法中加入sychronized关键字封锁的就是类本身。静态方法是所有类实例对象所共享的,因此线程对象在访问此静态方法时是互斥访问的,从而可以实现线程的同步,代码如下所示:
代码
package com.vista; class MyThread implements java.lang.Runnable { private int threadId; public MyThread(int id) { this.threadId = id; } @Override public void run() { taskHandler(this.threadId); } private static synchronized void taskHandler(int threadId) { for (int i = 0; i < 100; ++i) { System.out.println("Thread ID: " + threadId + " : " + i); } } }
public class ThreadDemo { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 10; ++i) { new Thread(new MyThread(i)).start(); Thread.sleep(1); } } } |