标签:一个 join 之间 stack 程序 start override 标记 lse
public class MyThread extends Thread {
public void run() {
for (int i = 0; i < 100; i++)
System.out.println(getName() + i);
}
}
// test
MyThread my1=new MyThread();//设置线程名
MyThread my2=new MyThread();
my1.setName("线程1 ");
my2.setName("线程2 ");
my1.start();
my2.start();
public class DeamonDemo implements Runnable{
@Override
public void run() {
for(int i = 0;i<100;i++)
System.out.println(Thread.currentThread().getName()+"---"+i);
}
}
// test
public class DeamonTest {
public static void main(String[] args) {
DeamonDemo d = new DeamonDemo();
Thread d1 = new Thread(d);
Thread d2 = new Thread(d);
d1.start();
d2.start();
}
}
DeamonDemo d = new DeamonDemo();
Thread d1 = new Thread(d);
Thread d2 = new Thread(d);
d1.setDaemon(true); // 设置守护线程
d2.setDaemon(true);
d1.start();
d2.start();
for(int i = 0;i<10;i++){
//打印main线程(主线程)线程名
System.out.println(Thread.currentThread().getName()+"---"+i);
}
PriorityDemo p = new PriorityDemo();
Thread tp1 = new Thread(p);
Thread tp2 = new Thread(p);
Thread tp3 = new Thread(p);
tp1.setName("xyg");
tp2.setName("wdf");
tp3.setName("OoO");
tp1.setPriority(10); // 最高优先级
tp2.setPriority(1);
tp3.setPriority(1);
tp1.start();
tp2.start();
tp3.start();
JoinDemo p = new JoinDemo();
Thread tp1 = new Thread(p);
Thread tp2 = new Thread(p);
Thread tp3 = new Thread(p);
tp1.setName("xyg");
tp2.setName("fuck");
tp3.setName("wdnmd");
tp1.setPriority(10);
tp2.setPriority(1);
tp3.setPriority(1);
tp1.start();
try {
tp1.join(); // 其他线程等待该线程终止
} catch (InterruptedException e) {
e.printStackTrace();
}
tp2.start();
tp3.start();
等待唤醒机制:
wait()和sleep()
public synchronized void set(String name, int age) {
//如果有数据则等待
if (flag) {
try {
wait(); // 线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//设置值
this.name=name;
this.age=age;
// 修改标记
flag = true;
notify();// 线程唤醒
}
...
public synchronized void get(){
//如果没有数据就等待
if(!flag){
try {
wait(); // 线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name+" "+age);
//修改标记
flag=false;
notify(); // 线程唤醒
}
public void run() {
for(int i = 0;i<100;i++){
System.out.println(Thread.currentThread().getName()+"---"+i);
Thread.yield(); //执行其他线程
}
}
1是否有共享数据
2是否多条语句操作共享数据
3是否在多线程环境中
...
public void run() {
if (x%2==0) {
//同步代码块
synchronized (this) {// 多个线程使用同一个锁对象
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + (ticket--) + "张票。");
}
}
}
public void run() {
check();
}
...
//同步方法
//同步方法的锁对象是this对象
//静态同步方法的锁对象是 类名.class Class类型对象
private synchronized void check() {
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + (ticket--) + "张票。");
}
}
注意:
标签:一个 join 之间 stack 程序 start override 标记 lse
原文地址:https://www.cnblogs.com/xiongyungang/p/12495740.html