多线程日记(17.5.3)

线程的run()和start()方法。

start()方法表示重新启用一个新的线程,新线程会掉用run()方法;run()方法就相当于一个普通的方法,可以重复进行调用。

public class Test {
    public static void main(String[]args){
        Thread thread=new NewThread("aa");
        thread.run();
        thread.start();
    }
}
class NewThread extends Thread{
    public NewThread(String name){
        super(name);
    }
    public void run(){
        System.out.println(Thread.currentThread().getName()+" is running");
    }
}

输出结果为main is running和aa isrunning,调用run()方法时,并不会重新开始一个新的线程,而是在已经运行的线程里调用run()方法,但是start()方法则是重新开始了一条新的线程。

synchronized总结(摘自http://www.cnblogs.com/skywang12345/p/3479202.html

在java中,每个对象都有一个同步锁且只有一个同步锁(同步锁是依赖于对象而存在的synchronized)。当我们去调用某个对象的synchronized时,就会获得该对象的同步锁。人不能两次踏入同一条河流,同样的当一个线程访问一个对象的同步锁时,另一个线程访问这个对象的同步锁就会被阻塞。

public class Test {
    public static void main(String[]args){
        NewThread obj=new NewThread();
        Thread thread1=new Thread(obj,"t1");
        Thread thread2=new Thread(obj,"t2");
        thread1.start();
        thread2.start();
    }
}
class NewThread implements Runnable{
    @Override
    public void run(){
        synchronized(this){
            for(int i=0;i<3;i++){
                System.out.println(Thread.currentThread().getName()+":"+(i+1));
            }
        }
    }
}

当线程thread1访问obj时,thread2就会被阻塞。

转载于:https://www.cnblogs.com/levi-ji/p/6802886.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值