1.线程和进程
线程:程序中单独顺序的控制流
线程本身依靠程序进行运行
线程是程序中的顺序控制流,只能使用分配给程序的资源和环境
进程:执行中程序
一个进程可以包含一个和多个线程
一个线程至少包含一个线程
2.线程的实现
在java中,线程实现的方法有2种
1)继承Thread类
public class ThreadDemo1 extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
}
}
2)实现Runnale方法
public class ThreadDemo1 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
}
}
3.线程的状态
1)创建状态:准备好了一个多线程的对象
2)就绪状态:调用了start()方法,等待CPU进行调度
3)运行状态:执行了run()方法
4)暂时停止运行,可能将资源交给其他线程运行
5)死亡状态:线程销毁
4.线程的常用方法
1)获取当前线程的名称
getName()
2)获得当前线程的对象
currentThread();
3)判断线程是否启动
isAlive()
4)线程的强行运行
join()
5)线程的休眠
sleep()
5. 线程的优先级
常见的线程优先级有
Thread.MAX_PRIORITY
<pre name="code" class="html">Thread.MIN_PRIORITY
Thread.NORM_PRIORITY
class ThreadDemo1 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0; i < 10; i++)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ffffffffffff");
}
}
}
class Test{
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadDemo1());
t1.setPriority(Thread.MAX_PRIORITY);
Thread t2 = new Thread(new ThreadDemo1());
t2.setPriority(Thread.MIN_PRIORITY);
Thread t3 = new Thread(new ThreadDemo1());
t3.setPriority(Thread.NORM_PRIORITY);
}
}
6.线程的同步
class ThreadTest implements Runnable {
private int ticket = 5;
@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0; i < 10; i++)
{
ticket(i);
}
}
private synchronized void ticket(int i) {
if(ticket > 0)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("车票 == "+ ticket--);
}
}
}
class ThreadDemo1{
public static void main(String[] args) {
ThreadTest testthread = new ThreadTest();
Thread t1 = new Thread(testthread);
Thread t2 = new Thread(testthread);
Thread t3 = new Thread(testthread);
t1.start();
t2.start();
t3.start();
}
}