package text;
public class ThreadTest {
/*进程是操作系统正在执行的不同的应用程序,线程是一个应用程序进程中不同的执行路径
* 主线程:即使java线程中没有显示的来声明一个线程,java也会有一个线程存在叫做主线程
* 使用Thead.currentThread()来获得当前线程
* ***************线程的创建方法:******************
* 1,继承Thread类。MyThread extends Thread ,需要覆盖run方法
* 2,实现Runnable接口。Runnable接口中有一个run()方法来定义线程执行代码:public void run()
* 线程的启动: 需要调用Thread的start方法,不能直接调用run方法,直接调用run方法,相当于方法的调用
* 线程的终止:当run方法返回,线程终止,一旦线程终止后不能再次启动,线程的终止可以调用线程的Interrupt方法,但这不是最佳方法,最好是设置一个标记来控制现成的终止
* 请解释:多线程的实现方式以及其区别:
* 多线程需要一个线程的主类,这个类要么继承Thread类,要么实现Runnable接口,法二比发一更好的实现数据共享的操作,并且可以避免单继承局限
*/
//实现线程名称的操作:构造方法:public Thread(Runnable target,String name);
// 设置名字:public final void setName(String name);
// 取得名字:public final String getName();
//
public static void main(String[] args) {
//实现Runnable接口
MyThread mt = new MyThread();
Thread th1 = new Thread(mt);
th1.setName("线程001");//给该线程设置名字
th1.start();
Thread th2 = new Thread(mt);
th2.setName("线程002");//给该线程设置名字
th2.start();
new Thread(mt,"线程c").start();
new Thread(mt,"线程a").start();
new Thread(mt,"线程b").start();
//继承Thread类
// MyThread1 mt1 = new MyThread1();
// mt1.start();
}
}
class MyThread implements Runnable{//表示实现多线程
private int ticket = 50;
@Override
public void run() {//覆写run方法,线程的主方法
for(int x = 0;x<50;x++){
//在多个线程访问统一资源的时候,一定要考虑到数据的同步问题,同步就使用synchronized关键字定义同步代码块或者同步方法。
//加入同步之后整个代码的而执行速度会变慢,因为多个线程会一起进入到方法之中,但同步操作属于线程安全的操作,异步属于非线程安全的操作
//程序中如果出现了过多的同步将产生死锁
synchronized(this){
if(this.ticket > 0)
try {
Thread.sleep(10);
System.out.println(Thread.currentThread().getName() //获得当前线程的名字
+ "卖票:ticket = "+this.ticket--);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class MyThread1 extends Thread{//表示实现多线程
private int ticket = 5;
@Override
public void run() {//覆写run方法,线程的主方法
for(int x = 0;x<50;x++){
if(this.ticket > 0)
try {
Thread.sleep(1000);//线程休眠,使线程延缓执行
//线程的休眠也有先后顺序
System.out.println("卖票:ticket = "+this.ticket--);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**********************线程的优先级**************************
* 理论上线程的优先级越高越有可能先执行
* 设置优先级:public final void setPriority(int newPriority)
* 取得优先级:public final int getPriority()
* 最高优先级:public static final int MAX_PRIORITY
* 中等优先级:public static final int NORM_PRIORITY
* 最低优先级:public static final int MIN_PRIORITY
*/
/*************线程一般依附于进程存在,但是现在进程在哪里呢?
* 每当使用java命令在JVM上解释一个程序执行的时候,都会默认启动线程,所以真个程序都跑在线程的运行机制上
* 每一个JVM会至少启动两个线程:主线程、GC线程
* */
Java线程
最新推荐文章于 2025-03-02 11:58:34 发布