1.多线程
1.extends Thread 在类中继承重写run方法
Test t = new test();
t.start();
2.implements Runable 在类中接口重写run方法
run.
Test t = new Test();
Thread t1 = new Thread((Runnable) t,"窗口1");
t1.start();
s1.start(); 分别开始运行
s2.start();
s1.getName() 获取线程的名称
s1.setName() 也可以代参设置线程名称
s1.getPriority() 获取线程优先级数
s1.setPriority(1-10) 设置线程优先级数 默认为5
Thread.sleep(100); 延迟多少毫秒输出,在类中使用
s1.join(); 先执行当前线程,在测试类使用
s1.setDaemon(true);
设置守护线程(当运行的都是守护线程就终止)
Thread.currentThread().getName()
获取当前正在执行的线程名称
Thread.currentThread().setName()
设置当前正在执行的主线程名称
@Override
public void run () {
cross();
private synchronized void cross () throws InterruptedException {
Thread.sleep(500);
renshu++;
System.out.println(Thread.currentThread().getName() + "他是第" + renshu + "位通过的");
??
Thread t = new Thread(s,"路人"+i);
t.start();
2.同步代码块,使安全
1.synchronized (obj) 锁对象
1.private int piao = 100; 无static
while (true) { 上面this,方法中是
if (x % 2 == 0) {
synchronized (this) { private synchronized void
if (piao > 0) {
Thread.sleep(100);
else {
sellpiao();
private synchronized void sellpiao () {
2.private static int piao = 100; 有static
while (true) { 上面方法.class,方法中是
if (x % 2 == 0) {
synchronized (类名.class) { private static synchronized void
if (piao > 0) {
Thread.sleep(100);
else {
sellpiao();
private static synchronized void sellpiao () {
线程安全的类:左边的
StringBuffer --- StringBuilder
Vector --- AarrayList
Hashtable --- HashMap
private Lock lock = new ReentrantLock();
lock.lock(); 锁住
while (true) {
try {
lock.lock();
if (piao > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "卖出第" + piao + "张票");
piao--;
}
} finally {
lock.unlock();
}
lock.unlock(); 释放
|
|