package test;

public class testThread
{
    public static void main(String[] args)
    {
        Example example = new Example();
        Example example2 = new Example();
        Thread1 thread1 = new Thread1(example);
        Thread1 thread2 = new Thread1(example2);
        thread1.start();
        thread2.start();
        
//        Example example = new Example();
//        Thread2 thread1 = new Thread2(example);
//        Thread2 thread2 = new Thread2(example);
//        thread1.start();
//        thread2.start();
    }

}



class Example
{
    public void execute()
    {
        for (int i = 0; i < 10; ++i)
        {
            try
            {
                Thread.sleep((long) Math.random() * 1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("Hello: " + i);
        }
    }

    public synchronized void execute2()
    {
        for (int i = 0; i < 10; ++i)
        {
            try
            {
                Thread.sleep((long) Math.random() * 1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("World: " + i);
        }
    }

}

class Thread1 extends Thread
{
    private Example example;

    public Thread1(Example example)
    {
        this.example = example;
    }

    @Override
    public void run()
    {
        example.execute();
    }

}

class Thread2 extends Thread
{
    private Example example;

    public Thread2(Example example)
    {
        this.example = example;
    }

    @Override
    public void run()
    {
        example.execute2();
    }

}

 

http://www.2cto.com/kf/201408/322243.html

http://www.mamicode.com/info-detail-517008.html

http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html

相关文章:

  • 2021-11-20
  • 2022-12-23
  • 2021-10-19
  • 2021-12-05
  • 2021-10-12
  • 2022-12-23
  • 2022-12-23
  • 2021-08-23
猜你喜欢
  • 2021-12-06
  • 2021-11-18
  • 2021-05-01
  • 2021-11-20
  • 2021-05-18
  • 2021-08-10
  • 2022-12-23
相关资源
相似解决方案