package com.haizhitao.thread;
public class ThreadTest4
{
public static void main(String[] args)
{
Example example = new Example();
TheThread t1 = new TheThread(example);
example = new Example();
TheThread2 t2 = new TheThread2(example);
t1.start();
t2.start();
}
}
class Example
{
public synchronized void execute()
{
for(int i = 0; i < 20; i++)
{
try
{
Thread.sleep((long)(Math.random() * 1000));
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hello: " + i);
}
}
public synchronized void execute2()
{
for(int i = 0; i < 20; i++)
{
try
{
Thread.sleep((long)(Math.random() * 1000));
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("world: " + i);
}
}
}
class TheThread extends Thread
{
private Example example;
public TheThread(Example example)
{
this.example = example;
}
@Override
public void run()
{
example.execute();
}
}
class TheThread2 extends Thread
{
private Example example;
public TheThread2(Example example)
{
this.example = example;
}
@Override
public void run()
{
example.execute2();
}
}
//output:
// world: 0
// world: 1
// hello: 0
// hello: 1
// world: 2
// hello: 2
// hello: 3
// world: 3
// world: 4
// hello: 4
// hello: 5
// world: 5
// world: 6
// world: 7
// world: 8
// hello: 6
// hello: 7
// world: 9
// hello: 8
// world: 10
// hello: 9
// world: 11
// hello: 10
// world: 12
// hello: 11
// world: 13
// world: 14
// hello: 12
// world: 15
// hello: 13
// world: 16
// hello: 14
// world: 17
// world: 18
// hello: 15
// world: 19
// hello: 16
// hello: 17
// hello: 18
// hello: 19
72
最新推荐文章于 2024-08-28 17:58:14 发布