线程组ThreadGroup
public class Test02 {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "线程,所属线程组:"
+ Thread.currentThread().getThreadGroup());
System.out.println(Thread.currentThread());
Thread.currentThread().setPriority(8);
Thread th=new Thread("mythread");
System.out.println(th.getPriority());
ThreadGroup tg = new ThreadGroup("wbs14061线程组");
System.out.println("tg线程组的父线程组:"+tg.getParent());
Thread th1=new Thread(tg, new MyThread2(), "first");
Thread th2=new Thread(tg, new MyThread2(), "second");
th1.setPriority(8);
tg.setMaxPriority(4);
th2.setPriority(9);
Thread th3=new Thread(tg, new MyThread2(), "third");
System.out.println("tg线程组的信息:"+tg);
th1.start();
th2.start();
th3.start();
}
}
class MyThread2 implements Runnable {
int num = 1;
@Override
public void run() {
while (num <= 100) {
System.out.println(Thread.currentThread().getName() + ","
+ Thread.currentThread().getPriority() + "****" + num++);
}
}
}
多线程访问共享数据
public class Test03 {
public static void main(String[] args) {
Ticket ticket = new Ticket();
Thread th1 = new Thread(ticket, "线程1");
Thread th2 = new Thread(ticket, "线程2");
Thread th3 = new Thread(ticket, "线程3");
th1.start();
th2.start();
th3.start();
}
}
class Ticket implements Runnable {
private int num = 100;
Object obj = new Object();
@Override
public void run() {
while (true) {
synchronized (obj) {
if (num > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "售出车票:" + num--);
}
}
}
}
}
synchronized 方法
public class Test04 {
public static void main(String[] args) {
Account account=new Account();
Thread th1=new Thread(account, "你爸");
Thread th2=new Thread(account, "你妈");
th1.start();
th2.start();
}
}
class Bank {
private double balance;
public void getBalance() {
System.out.println("当前余额:" + balance);
}
public void setBalance(double money) {
balance = balance + money;
}
}
class Account implements Runnable {
private static Bank bank = new Bank();
static int i = 1;
@Override
public void run() {
while (true) {
saveMoney();
}
}
public static synchronized void saveMoney(){
if (i <= 3) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
bank.setBalance(300);
System.out.println(Thread.currentThread().getName()
+ "存了300元,第" + (i++) + "次");
bank.getBalance();
} else {
System.exit(0);
}
}
}