进程:进程就是正在运行的程序,程序是一个没有生命的实体,只有处理器赋予程序生命时,它才能成一个活动的实体,我们称之为进程,比如在Windows系统中,一个运行的.exe就是进程
线程:进程中的一个执行任务,负责当前进程中程序的执行,一个进程至少有一个线程,一个进程可以运行多个线程,多个线程共享数据。
发起线程的两种方式:
- 创建一个类继承自Thread,重写run方法,调用该类时使用start方法
public class A
{
public static void main(String[] args)
{
new Thread1().start();
new Thread2().start();
}
}
class Thread1 extends Thread
{
@Override
public void run()
{
while(true)
{
System.out.println("线程1");
try
{
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Thread2 extends Thread
{
@Override
public void run()
{
while(true)
{
System.out.println("线程2");
try
{
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
匿名内部类写法
public class A
{
public static void main(String[] args)
{
new Thread()
{
@Override
public void run()
{
while(true)
{
System.out.println("线程1");
try
{
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}.start();
new Thread()
{
@Override
public void run()
{
while(true)
{
System.out.println("线程2");
try
{
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}.start();
}
}
2.创建一个类实现Runnable接口并传入Thread对象,调用类时使用start方法 例
public class B
{
public static void main(String[] args)
{
long begin1 = System.currentTimeMillis();
Thread thread = new Thread(new MyRunnable());
thread.start();
System.out.println("主程序时间"+(System.currentTimeMillis()-begin1));
}
}
class MyRunnable implements Runnable
{
@Override
public void run()
{
long begin = System.currentTimeMillis();
for (int i = 0; i < 10; i++)
{
System.out.println("线程一");
try
{
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("线程时间"+(System.currentTimeMillis()-begin));
}
}
匿名内部类写法
public class B
{
public static void main(String[] args)
{
long begin1 = System.currentTimeMillis();
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
long begin = System.currentTimeMillis();
for (int i = 0; i < 10; i++)
{
System.out.println("线程一");
try
{
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("线程时间"+(System.currentTimeMillis()-begin));
}
});
thread.start();
System.out.println("主程序时间"+(System.currentTimeMillis()-begin1));
}
}
推荐第二种方式,可以实现多个接口
Thread的一些方法
start();标记线程为就绪态,等待cpu执行
run();执行方法,线程中执行的内容需要写到该方法中
static yield();谦让暗示
static sleep()/join();线程等待
stop();结束线程(不推荐)
isAlive();判断一个线程是否还在执行
setPriority();设置线程优先级(分为0-9)
线程的几种状态:新建(new Thread),就绪(.start();此时未分配到cpu资源),运行(.run();分配到cpu资源),阻塞(sleep或join方法,可认为临时中止了自身进程的运行,释放了cpu资源),死亡(线程完成后的结束或人为干预或遇到异常的结束)
sleep函数和wait的区别
sleep属于Thread类,wait属于Object类
sleep运行时不会释放线程锁,wait会放弃对象锁
start和run的区别
用start方法来启动线程,线程处于就绪态,并未开始运行
方法run()又叫线程体,包含了要执行这个线程的内容,线程进入运行状态,开始运行run中的代码,run方法结束,程序运行终止,然后cpu再调度其他线程.