#实现方法一,继承Thread 复写run
class A extends Thread{
public void run()
{
for(int i=0;i<100;i++)
{
try
{
Thread.sleep(100);
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("thread run:"+i);
}
}
}
//test 代码
class Test{
public static void main(String[] args)
{
A a= new A();
a.start();
for(int i=0;i<100;i++)
{
try
{
Thread.sleep(100);
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("main run:"+i);
}
}
}
#实现方法2,实现接口Runnable, 把接口传入线程中
class A implements Runnable{
public void run()
{
for(int i=0;i<100;i++)
{
try
{
Thread.sleep(100);
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("thread run:"+i);
}
}
}
//测试程序
class Test{
public static void main(String[] args)
{
A aa=new A();
Thread a= new Thread(aa);
a.start();
for(int i=0;i<100;i++)
{
try
{
Thread.sleep(100);
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("main run:"+i);
}
}
}
#多线程竞争
//没有使用同步信号
class A implements Runnable{
int i=0;
public void run()
{
for(;i<100;i++)
{
Thread.yield();
System.out.println(Thread.currentThread().getName()+"thread run:"+i);
}
}
//使用同步信号
class A implements Runnable{
int i=0;
public void run()
{
while(true)
{
synchronized(this)
{
Thread.yield();
System.out.println(Thread.currentThread().getName()+"thread run:"+i);
i++;
if(i>100)
{
break;
}
}
}
}
}
//测试竞争代码
class Test{
public static void main(String[] args)
{
A aa=new A();
Thread a= new Thread(aa);
Thread b= new Thread(aa);
a.start();
b.start();
}
}
本文介绍Java中创建线程的两种方法:继承Thread类与实现Runnable接口,并通过实例展示。此外,探讨了多线程环境下的竞态条件,包括同步与非同步信号的使用,以及如何在多线程环境中正确地更新共享资源。

343

被折叠的 条评论
为什么被折叠?



