---------------------------------------------------------------- android培训、java培训、期待与您交流! ----------------------------------------------------------------------------------------
线程是进程的分割,是计算机进行调度的基本单位,一个进程可以包含一个或多个线程,有了线程程序的运行效率变快了。在java中线程的定义,可以通过两种方法,一种是通过继承Thread类,另一种是通过实现Runnalbe接口。示例如下:
class Test3
{
public static void main(String[] args)
{
ThreadDemo t1=new ThreadDemo();
t1.start();
ThreadDemo2 td=new ThreadDemo2();
Thread t2=new Thread(td);
t2.start();
}
}
class ThreadDemo extends Thread//继承Thread类以实现进程的创建
{
public void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+"方法一");
}
}
}
class ThreadDemo2 implements Runnable//实现Runnable接口以实现进程的创建
{
public void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+"方法二");
}
}
}
进程的开启只能用start()方法, 虽然类中的run()方法可以调用,但是并不会开启一个进程。
进程间的同步:
一种是通过同步代码块,另一种是通过同步函数
class Test3
{
public static void main(String[] args)
{
ThreadDemo1 td1=new ThreadDemo1();
Thread t1=new Thread(td1);
Thread t2=new Thread(td1);
Thread t3=new Thread(td1);
t1.start();
t2.start();
t3.start();
}
}
class ThreadDemo1 implements Runnable
{
public void run()
{
int x=1000;
while(x>0)
{
synchronized(Test3.class)
{
System.out.println(Thread.currentThread().getName()+"-----"+x--);
}
}
}
public void synchronized run()
{ int x=1000;
while(x>0)
{
System.out.println(Thread.currentThread().getName()+"-----"+x--);
}
}
}
---------------------------------------------------------------- android培训、java培训、期待与您交流! ----------------------------------------------------------------------------------------