标签:string oid pre 表示 类方法 设置线程优先级 控制 block state
Runnable
是Java中所有线程相关的类必须实现的接口
有两种方式,继承Thread
类和实现Runnable
接口
public class Main extends Thread{
@Override
public void run() {
//调用getName()返回线程名称
System.out.println(getName() + " is running");
}
public static void main(String[] args) {
//实例化Main对象
Main one = new Main();
Main two = new Main();
Main three = new Main();
//启动线程
one.start();
two.start();
three.start();
}
}
public class Main implements Runnable{
@Override
public void run () {
//Thread的类方法Thread.currentThread()返回当前线程对象,再调用getName()返回线程名称
System.out.println(Thread.currentThread().getName() + " is running");
}
public static void main(String[] args) {
//实例化Main类
Main one = new Main();
Main two = new Main();
Main three = new Main();
//将Main的实例代入Thread构造函数,构造出Thread对象
Thread the_one = new Thread(one);
Thread the_two = new Thread(two);
Thread the_three = new Thread(three);
//启动线程
the_one.start();
the_two.start();
the_three.start();
}
}
//个线程间共享用于控制循环的变量i
public class Main implements Runnable{
// 这里的变量就是属于共享资源
int i=0;
// run方法内部是每个线程内部的资源和代码
@Override
public void run() {
// Thread的类方法Thread.currentThread()返回当前线程对象,再调用getName()返回线程名称
// System.out.println(Thread.currentThread().getName()+" is running");
for (; i < 10; i ++) {
System.out.println(Thread.currentThread().getName() + " is running for the "+i);
}
// System.out.println(message);
}
public static void main (String[] args) {
//实例化Main类
Main one = new Main();
// Main two=new Main();
// Main three=new Main();
//将Main的实例代入Thread构造函数,构造出Thread对象
Thread the_one = new Thread(one);
Thread the_two = new Thread(one);
Thread the_three = new Thread(one);
//启动线程
System.out.println(the_one.getId());
System.out.println(the_two.getId());
System.out.println(the_three.getId());
the_one.start();
the_two.start();
the_three.start();
}
}
//setPriority()设置,参数可以是常量也可以是[1,10]整数
the_one.setPriority(Thread.MAX_PRIORITY);
System.out.println(the_one.getPriority()); //输出打印10
优先级常量有三个等级
使用synchronized
修饰符,可修饰方法和语句块
修饰方法
//object method
public synchronized void printEach() {
//once for loop
}
//static method
public static synchronized void printEach() {
//once for loop
}
//statement block
//this表示为当前对象,也可以使用别的对象作为参数
synchronized(this) {
//code
}
标签:string oid pre 表示 类方法 设置线程优先级 控制 block state
原文地址:https://www.cnblogs.com/esrevinud/p/11823752.html