编程语言
首页 > 编程语言> > java学习(161):同步代码块

java学习(161):同步代码块

作者:互联网

public class SynCode implements Runnable{
    public void run(){
        synchronized (this){
            Thread current=Thread.currentThread();//获取当前线程
            for(int i=1;i<10;i++){
                System.out.println( "当前执行代码块的名称为" +current.getName());
                try {
                    Thread.sleep( 1000 );
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

测试类

//同步代码块
public class test108 {
    public static void main(String[] args){
        SynCode synCode=new SynCode();
        Thread t0=new Thread( synCode,"歌谣" );
        Thread t1=new Thread(  synCode,"东方不败");
        Thread t2=new Thread( synCode ,"火运");
        t2.setPriority( Thread.MAX_PRIORITY );
        t2.start();
        t1.start();
        t0.start();
    }
}

运行结果

标签:同步,java,Thread,synCode,public,start,new,SynCode,161
来源: https://blog.csdn.net/weixin_43392489/article/details/100876449