public class ThreadTest {
public static void main(String[] args){
// System.out.println("HelloWorld");
Counter c = new Counter();
Thread n1 = new Thread(new Run(c));
n1.setName("n1");
Thread n2 = new Thread(new Run(c));
n2.setName("n2");
n1.start();
n2.start();
/* Thread n3 = new Thread(new Run(c));
n3.setName("n3");
Thread n4 = new Thread(new Run(c));
n4.setName("n4");
Thread n5 = new Thread(new Run(c));
n5.setName("n5");
*/
try{
Thread.currentThread().sleep(1000);
}catch(InterruptedException e){}
/*
Thread st = new SonThread("SonThread start");
st.start();
System.out.println(Thread.currentThread()); //拿到当前的线程
try{
Thread.sleep(1000);
// st.join(); //线程合并
}catch(InterruptedException e){
e.printStackTrace();
}
st.interrupt();
*/
}
}
class Run implements Runnable{
String printText;
Counter c;
Run(String printText){
this.printText = printText;
}
Run(Counter c){
this.c = c;
}
@Override
public void run() {
if(Thread.currentThread().getName().equals("n2")){
c.test2();
}else{
c.test();
}
}
}
class SonThread extends Thread{
String printText;
SonThread(String printText){
this.printText = printText;
}
@Override
public void run() {
yield();
System.out.println(printText);
System.out.println(isAlive());
System.out.println(getPriority());
try{
sleep(5000);
System.out.println("5秒等待完毕!");
}catch(InterruptedException e){
e.printStackTrace();
return;
}
}
@Override
public synchronized void start() {
super.start();
System.out.println("线程启动后我还要干一点事情……");
}
}
class Counter{
private int num = 0;
public void add(){
synchronized(this) {
num++;
System.out.println("当前线程名:" + Thread.currentThread().getName() + " num当前值:" + num);
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
}
}
}
public void test(){
synchronized (this){
System.out.println("同步调试");
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) { }
}
}
public void test2(){
synchronized (this) {
System.out.println("同步调试222");
}
}
}
/*
* synchronized 对象锁是此对象所拥有的一把锁,其他同步代码都会受到这一把锁的影响
* 线程开启的两种方式 一种是实现Runnable接口 另一种则是继承Thread线程
* synchronized 只锁定被圈定的代码段 其他未被圈定的代码不受影响
* 多线程同时调用synchronized线程锁的代码,会被放入等待锁池中
*
* */
网友评论