多线程之线程同步(一)

<code>synchronized修饰一个静态的方法.
静态方法是属于类的而不属于对象的。同样的,synchronized修饰的静态方法锁定的是这个类的所有对象/<code>


<code>public synchronized static void method() {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace(); }
}
}

// 如果使用run()来启动线程,就不是异步执行了,而是同步执行,不会达到使用线程的意义。
public synchronized void run() {
method();
}/<code>
<code>private static int count;
public Thr() {
count = 0;
}

public static void main(String [] args){
// Thr implements Runnable;Thread类本身也是实现了Runnable接口
Thr th = new Thr();
Thr th2 = new Thr();
Thread thread = new Thread(th,"t1");
Thread thread2 = new Thread(th2,"t2");
// 启动线程 ,出现异步执行的效果
thread.start();
thread2.start();}/<code>

run:

多线程之线程同步(一)


补充:1.Thread类本身也是实现了Runnable接口.

2.如果使用run()来启动线程,就不是异步执行了,而是同步执行,不会达到使用线程的意义。

3.调用线程的start方法是创建了新的线程,在新的线程中执行。
调用线程的run方法是在主线程中执行该方法,和调用普通方法一样,


分享到:


相關文章: