package 多线程;
/*
* 类锁,类只有一个所以锁是类的级别,也只有一个
*
* 对象不同也得等,应为用的是类锁
*/
public class ThreadTest17
{
public static void main(String[] args) throws Exception
{
Thread t1 = new Thread(new proo());
Thread t2 = new Thread(new proo());
t1.setName("t1");
t2.setName("t2");
t1.start();
Thread.sleep(1000);
t2.start();
}
}
class proo implements Runnable
{
public void run()
{
if("t1".equals(Thread.currentThread().getName())) {
MyClass.m1();
}
if("t2".equals(Thread.currentThread().getName())) {
MyClass.m2();
}
}
}
class MyClass
{
//将synchronized添加到静态方法上去,线程执行到此方法会找类锁
public synchronized static void m1()
{
try {Thread.sleep(4000);}catch(Exception e) {}
System.out.println("m1----");
}
/*//不会等m1结束,因为该方法没有被synchronized修饰
public static void m2()
{
System.out.println("m2----");
}
*/
//m2要等m1执行结束之后再执行,该方法有synchronized
public synchronized static void m2()
{
System.out.println("m2----");
}
}
package 多线程;
/*
* 守护线程
* 其他所有的用户线程结束,则守护线程退出
* 守护线程一般都是无限执行的
*/
public class ThreadTest18
{
public static void main(String[] args) throws Exception
{
Thread t1 = new porrs();
t1.setName("t1");
t1.setDaemon(true);
t1.start();
for(int i = 0; i < 5; i ++) {
System.out.println(Thread.currentThread().getName()+"-->"+i);
Thread.sleep(1000);
}
}
}
class porrs extends Thread
{
public void run()
{
int i = 0;
while(true) {
i ++;
System.out.println(Thread.currentThread().getName()+"-->"+i);
try{Thread.sleep(500);} catch(Exception e) {}
}
}
}