线程常用的操作方法,基本操作都是在Thread类中实现!
第一个方法:得到线程的名称
构造方法 :public Thread(Runnable target,String name)
取得名称: public final void setName(String name)class Mythread extends Thread
{
private int ticket = 10;
public void run()
{
for(int i=0; i<5; i++)
System.out.println("当前线程名称:"+ currentThread(). getName());
}
}
class Mythread Demo
{
public static void main(String[] args)
{
Mythread mt1 = new Mythread();
new Thread(mt1,"我的线程").start();
mt1.start();
}
}
运行结果:
---------- java运行 ----------
当前线程名称:我的线程
当前线程名称:我的线程
当前线程名称:Thread-0
当前线程名称:我的线程
当前线程名称:我的线程
当前线程名称:我的线程
当前线程名称:Thread-0
当前线程名称:Thread-0
当前线程名称:Thread-0
当前线程名称:Thread-0
输出完成 (耗时 0 秒) - 正常终止
线程休眠:
class MyRunnableDemo
{
public static void main(String[] args)
{
Mythread mt1 = new Mythread();
new Thread(mt1,"我的线程A").start();
new Thread(mt1,"我的线程B").start();
new Thread(mt1,"我的线程C").start();
new Thread(mt1,"我的线程D").start();
new Thread(mt1,"我的线程E").start();
new Thread(mt1,"我的线程F").start();
new Thread(mt1,"我的线程G").start();
new Thread(mt1,"我的线程H").start();
mt1.start();
}
}
class Mythread extends Thread
{
public void run()
{
for(int i=0; i<5; i++)
{
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("当前线程名称:"+currentThread().getName()+"x=:"+i);
}
}
}
运行结果:
---------- java运行 ----------
当前线程名称:我的线程Ax=:0
当前线程名称:我的线程Fx=:0
当前线程名称:我的线程Gx=:0
当前线程名称:我的线程Ex=:0
当前线程名称:我的线程Cx=:0
当前线程名称:我的线程Dx=:0
当前线程名称:我的线程Bx=:0
当前线程名称:我的线程Hx=:0
当前线程名称:Thread-0x=:0
当前线程名称:我的线程Fx=:1
当前线程名称:我的线程Cx=:1
当前线程名称:我的线程Ax=:1
当前线程名称:我的线程Ex=:1
当前线程名称:我的线程Gx=:1
当前线程名称:我的线程Dx=:1
当前线程名称:Thread-0x=:1
当前线程名称:我的线程Bx=:1
当前线程名称:我的线程Hx=:1
当前线程名称:我的线程Cx=:2
当前线程名称:我的线程Fx=:2
当前线程名称:我的线程Ex=:2
当前线程名称:我的线程Gx=:2
当前线程名称:我的线程Ax=:2
当前线程名称:我的线程Hx=:2
当前线程名称:Thread-0x=:2
当前线程名称:我的线程Bx=:2
当前线程名称:我的线程Dx=:2
当前线程名称:我的线程Cx=:3
当前线程名称:我的线程Gx=:3
当前线程名称:我的线程Fx=:3
当前线程名称:我的线程Ax=:3
当前线程名称:我的线程Ex=:3
当前线程名称:我的线程Bx=:3
当前线程名称:Thread-0x=:3
当前线程名称:我的线程Hx=:3
当前线程名称:我的线程Dx=:3
当前线程名称:我的线程Gx=:4
当前线程名称:我的线程Cx=:4
当前线程名称:我的线程Fx=:4
当前线程名称:我的线程Ax=:4
当前线程名称:我的线程Ex=:4
当前线程名称:Thread-0x=:4
当前线程名称:我的线程Dx=:4
当前线程名称:我的线程Bx=:4
当前线程名称:我的线程Hx=:4
输出完成 (耗时 50 秒) - 正常终止
结论:同时休眠!!!
线程优先级:
Thread.MIN_PRIORITY =1
Thread.
NORM_PRIORITY =5
NORM_PRIORITY =5
Thread.
MAX_PRIORITY = 10
MAX_PRIORITY = 10
MAX_PRIORITY = 10
理论,优先级高的“线程”先被执行。
但是,手动设置优先级,可能修改不成功!!!
主方法的线程优先级 是 5
Thread.currentThread().getPriority
线程的同步和死锁问题:
同步2中实现 1)通过代码块实现 (同步代码块) 2)同步方法
多个线程对同一个资源的操作,要注意什么问题??
考虑同步的问题。但是过多的同步,会造成死锁问题!