java 多线程 sync

package test.sync;

public class TT implements Runnable {

int b = 100;

public synchronized void m1() {
b = 1000;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("b = " + b);
}

public synchronized void m2() {
b = 2000;
System.out.println(b);
}


@Override
public void run() {
m1();
}

/**
* @param args
*/
public static void main(String[] args) {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tt.m2();
}


}

----------------------------------------------------------------------------------
输出:
b = 1000
2000
----------------------------------------------------------------------------------
t这个线程对象调用start方法后,主线程睡眠了,这个时候t就真正的被cpu调度了。
紧接着就到了run方法里 run方法里调用了m1方法,然后m1 m2方法都被锁住了
tt.m2就得等待,也就是说主线程需要等到m1执行完后才能执行m2方法
synchronized是锁住当前对象的带synchronized关键字的方法
它是互斥锁 对象级的


package test.sync;

public class TestSync implements Runnable {

Timer timer = new Timer();

public static void main(String[] args) {
TestSync test = new TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}

public void run() {
timer.add(Thread.currentThread().getName());
}
}

class Timer {
private static int num = 0;

public synchronized void add(String name) { //对象锁 互斥锁
num++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
System.out.println(name + ", 你是第" + num + "个使用timer的线程");
}
}
运行效果是:
t1, 你是第1个使用timer的线程
t2, 你是第2个使用timer的线程
这个同步方法是锁定当前对象的意思,也就是timer
因为t1,t2都是用的同一个target也就是同一个test,那么也就是同一个timer


package test.sync;

public class TestSync implements Runnable {

Timer timer = new Timer();

public static void main(String[] args) {
[color=red] TestSync test1 = new TestSync();
TestSync test2 = new TestSync();[/color]
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test2);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}

public void run() {
timer.add(Thread.currentThread().getName());
}
}

class Timer {
private static int num = 0;

public synchronized void add(String name) { //对象锁 互斥锁
num++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
System.out.println(name + ", 你是第" + num + "个使用timer的线程");
}
}

上面程序的运行效果:
t1, 你是第2个使用timer的线程
t2, 你是第2个使用timer的线程
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值