java 一道线程面试题

  1. public class TestThread implements Runnable{
  2.     //int b=100;
  3.     private TestMy tm=new TestMy();
  4. public void run(){
  5.     tm.m1();
  6. }
  7. public void callm2(){
  8.     tm.m2();
  9. }
  10. public void main(String []args){
  11.     System.out.println("hello");
  12.     TestThread th=new TestThread();
  13.     Thread t1=new Thread(th);
  14.     t1.start();
  15.     th.callm2();
  16. }
  17. }
  18. class TestMy{
  19.     int b=100;
  20.     public synchronized void m1(){
  21.         System.out.println("m1 method start");
  22.         b=1000;
  23.         try{
  24.             Thread.sleep(5000);
  25.         }
  26.         catch(InterruptedException e){
  27.             
  28.         }
  29.         System.out.println(b);
  30.         System.out.println("m1 method over");
  31.     }
  32.     public void m2(){
  33.     System.out.println("m2 method start");
  34.     System.out.println(b);
  35.     System.out.println("m1 method over");
  36.     
  37.     }
  38.     
  39. }

总结:

祝线程和被创建的线程之间,一个是调用对象的synchronized方法

一个是调用同一个对象的非synchronized方法,这个时候二者之间并没有实现同步,估计应该和二者都没有加

同步关键字synchronized的效果一样

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值