JAVA 线程同步异步简单实例

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 = ; i < ; ++i)
{
try
{
Thread.sleep((long) Math.random() * );
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Hello: " + i);
}
} public synchronized void execute2()
{
for (int i = ; i < ; ++i)
{
try
{
Thread.sleep((long) Math.random() * );
}
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

上一篇:dubbo could not get local host ip address will use 127.0.0.1 instead 异常处理


下一篇:Android Studio经常使用操作技巧(不断更新)