多线程打印

Posted Panda_Java

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程打印相关的知识,希望对你有一定的参考价值。

两个线程交替打印1到100

1 两个线程交替打印1到100

static volatile int falg = 0;
    @Test
    public void test001()

        Thread threadA = new Thread(new Runnable() 
            @Override
            public void run() 
                int i = -1;
                while(i < 100) 
                    if(KinglexCompanyExecutorApplicationTests.falg == 0)
                        i = i + 2;
                        System.out.println(i);
                        KinglexCompanyExecutorApplicationTests.falg = 1;
                    
                
            
        );
        threadA.start();
        Thread threadB = new Thread(new Runnable() 
            @Override
            public void run() 
                int i = 0;
                while(i < 100)
                    if(KinglexCompanyExecutorApplicationTests.falg == 1)
                        i = i + 2;
                        System.out.println(i);
                        KinglexCompanyExecutorApplicationTests.falg = 0;
                    
                
            
        );
        threadB.start();
    

2 三个线程交替打印a、b、c

  static volatile int falg = 0;
    @Test
    public void test001()

        Thread threadA = new Thread(new Runnable() 
            @Override
            public void run() 
                int i = 0;
                while(i < 100) 
                    if(KinglexCompanyExecutorApplicationTests.falg == 0)
                        i = i + 1;
                        System.out.println('a');
                        KinglexCompanyExecutorApplicationTests.falg = 1;
                    
                
            
        );
        threadA.start();
        Thread threadB = new Thread(new Runnable() 
            @Override
            public void run() 
                int i = 0;
                while(i < 100)
                    if(KinglexCompanyExecutorApplicationTests.falg == 1)
                        i = i + 1;
                        System.out.println('b');
                        KinglexCompanyExecutorApplicationTests.falg = 2;
                    
                
            
        );
        threadB.start();
        Thread threadC = new Thread(new Runnable() 
            @Override
            public void run() 
                int i = 0;
                while(i < 100)
                    if(KinglexCompanyExecutorApplicationTests.falg == 2)
                        i = i + 1;
                        System.out.println('c');
                        KinglexCompanyExecutorApplicationTests.falg = 0;
                    
                
            
        );
        threadC.start();
    

以上是关于多线程打印的主要内容,如果未能解决你的问题,请参考以下文章

多线程打印

Java多线程通信之两个线程分别打印AB各10次

多线程-线程一打印1,2,3,4,5线程二打印6,7,8,9,10,线程三打印11,12,13,14,15,...直到45结束

多线程打印宝典

java多线程 线程八锁

多线程按顺序打印数字,支持配置线程数目和打印数字结尾