1.创建线程的两种方法
第一种创建线程方法是通过继承Thread来实现的
//Mythread类
package Thread;
public class MyThread extends Thread {
private String name;
public MyThread(String name)
{
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("我是线程"+name+"编号:"+i);
}
super.run();
}
}
//主函数
//线程的启动必须要用start,不可以使用run,使用线程,必须重写run方法
package Thread;
public class ThreadCreat {
public static void main(String[] args) {
MyThread t1 = new MyThread("A");
MyThread t2 = new MyThread("B");
t1.start();
t2.start();
}
第二种创建线程方法是通过实现Runnable接口实现的
第一种创建线程的方法是通过直接创建线程,然后重写run方法使用的,也就是说第一种方法的源代码中Thread类中的run方法里面的target为空来构建的,第二种方法是通过Thread类然后向其构造函数传入Runnable对象,使其Thread类中的run方法里的target对象部位null而创建的,然后在重写Runnable里面的run方法,通过target调用run方法实现线程的运行。
//继承并实现Runnable接口
package Thread;
public class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("我是线程"+name+" 编号:"+i);
}
}
}
//主函数
package Thread;
public class ThreadCreat {
public static void main(String[] args) {
MyRunnable mr1 = new MyRunnable("A");
MyRunnable mr2 = new MyRunnable("B");
Thread t1 = new Thread(mr1);
Thread t2 = new Thread(mr2);
t1.start();
t2.start();
}
}
2.线程的两种状态
- 创建状态:线程已经完成创建,也就是说对象已经创建好了
- 就绪状态:调用了start方法,但是当前CPU没有资源或者手动暂停或者其他一些因素,进而导致无法运行该线程
- 运行状态:执行了run方法
- 终止状态(死亡状态):线程销毁
3.线程的常用方法
- 获取线程名称Thread.currentThread().getName()
- 取得当前线程对象Thread.currentThread()
- 判断线程是否启动,就是用对象调用该isAlive()方法来确定是否启动
- 线程的强行运行,也是用对象调用join()方法来让当前对象强行运行
- 线程的休眠,Thread.sleep(ms)
- 线程的礼让,Thread.yield()
4.线程的优先级
1-MIN_PRIORITY , 10-MAX_PRIORITY , 5-NORM_PRIORITY,优先级高只能说更大可能抢到资源,并不能百分之百拿到CPU 资源,默认优先级是NORM_PRIORITY,使用是对象调用setPriority方法
5.线程之间互斥(使用synchronized关键字锁定线程要共享的资源,一种是对资源锁定,一种是对方法锁定)
静态方法在运行的时候不用创建类的实例化对象
package TimerTest;
public class TraditionalThreadSynchronized {
public static void main(String[] args) {
new TraditionalThreadSynchronized().init();
}
public void init() {
Output output = new Output();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
output.output("abcd");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
Output output = new Output();
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
output.output("1234");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
class Output{
String xxx = "";
public void output(String name) {
int len = name.length();
synchronized (xxx) {//也可以使用this来指定对应的对象,或者用public synchronized void output()将整个方法锁起来
for(int i = 0; i<len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
}
359

被折叠的 条评论
为什么被折叠?



