线程的命名与取得
Thread类中,有关于线程名字设置的构造方法,成员方法(getName(),setName())。
有关获取当前线程的静态方法(.currentThread())。
package wzr.study02.Thread;
public class ThreadNameAndUse {
public static void main(String[] args) {
MyThreadA mt=new MyThreadA();
new Thread(mt,"MythreadA1").start();
mt.run();
}
}
class MyThreadA implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
如果直接调用run()方法,则输出名字main,说明main函数也是一个线程,那么main的进程?每当使用java命令执行java程序时,就会启动一个JVM进程,一台电脑可以启动多个JVM进程。而JVM中,主线程可以创建多个子线程。
主线程负责总体流程控制,子线程负责处理耗时操作。
线程休眠
Thread.sleep(毫秒,纳秒);
Thread.sleep(毫秒);
休眠的特点:时间一到自动唤醒。
休眠可能有Exception的异常。
线程中断
- 判断线程是否被中断:public boolean IsInterrupted()
- 中断线程执行:public void interrupt()
所有正在执行的进程都是可以被中断 的,中断进程必须进行异常 的处理。
package wzr.study02.Thread;
public class ThreadNameAndUse {
public static void main(String[] args) {
Thread td=new Thread(()->{
System.out.println("休息十秒");
try {
Thread.sleep(10000);
System.out.println("真不戳");
} catch (InterruptedException e) {
System.out.println("谁打扰我!");
e.printStackTrace();
}
});
Thread tdd=new Thread(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("被发现了!");
e.printStackTrace();
}
if(!td.isInterrupted()) {
td.interrupt();
}
});
td.start();
tdd.start();
}
}
线程强制运行
满足某些条件时,线程可以独占资源,直至线程执行结束。
强制执行:public final void join() throws InterruptedException;
只有在获取强制执行线程对象时才可以执行join()
package wzr.study02.Thread;
public class ThreadNameAndUse {
public static void main(String[] args) {
Thread tdd=new Thread(()->{
for(int i=0;i<30;i++) {
try {
Thread.sleep(100);
System.out.println("抢到了"+i);
} catch (InterruptedException e) {
System.out.println("被发现了!");
e.printStackTrace();
}
}
});
Thread td=new Thread(()->{
for(int i=0;i<30;i++) {
if(i==15) {
try {
tdd.join();
} catch (InterruptedException e) {
System.out.println("没抢到~");
e.printStackTrace();
}
}
try {
Thread.sleep(100);
System.out.println("针不戳"+i);
} catch (InterruptedException e) {
System.out.println("谁搞我!");
e.printStackTrace();
}
}
});
td.start();
tdd.start();
}
}
线程让步
Thread.yield():
public static void yield();每次yield都只会让步一次当前资源。
线程优先级
理论上,优先级高的先执行。(有可能但不绝对)。
设置优先级:public final void setPriority(int newPriority);
获取优先级:public final int getPriority();
Thread中的常量:
最高优先级:MAX_PRIORITY=10;
中间优先级:NORM_PRIORITY=5;
最低优先级:MIN_PRIORITY=1;
主线程和默认线程(new Thread())是中间的优先级。
同步问题引出
买票系统
package wzr.study03.MultiThread;
public class Sell {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread mt=new MyThread();
new Thread(mt,"A").start();
new Thread(mt,"B").start();
new Thread(mt,"C").start();
}
}
class MyThread implements Runnable{
private int ticket=5;
@Override
public void run() {
while(ticket>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖票"+ticket--);
}
}
}
问题:出现相同票数或负数,0票。