* Thread类的基本获取和设置方法
public final String getName()//获取线程名称
public final void setName(String name)//设置线程名称
public static Thread currentThread()//获取当前执行的线程
线程优先级的获取和设置线程优先级
如何设置和获取线程优先级
public final int getPriority() //获取线程的优先级
public final void setPriority(int newPriority)//设置线程的优先级
注意事项: 有的时候我们给线程设置了指定的优先级,但是该线程并不是按照优先级高的线程执行,那是为什么呢?
因为线程的优先级的大小仅仅表示这个线程被CPU执行的概率增大了.但是我们都知道多线程具有随机性,
* 获取线程的优先级:
public final int getPriority()返回线程的优先级。
* 线程的默认优先级是5
* 给线程设置优先级:
public final void setPriority(int newPriority)
线程控制之休眠线程
* 线程休眠: public static void sleep(long millis) 线程休眠
//线程会休眠相应时间的时间然后再去执行
线程控制之加入线程
* 加入线程: public final void join()
//在该方法的调用者调用执行结束后其他的线程才能进行,在start执行之后
线程控制之守护线程
守护线程: public final void setDaemon(boolean on):
将该线程标记为守护线程或用户线程。当正在运行的线程都是守护线程时,Java 虚拟机退出。
//在start执行之前
//设置守护线程后,主线程结束,守护线程也会结束
Java守护线程和Linux守护进程
两者不是一个概念。Linux守护进程是后台服务进程,没有控制台。
在Windows中,你可以运行javaw来达到释放控制台的目的,在Unix下你加&在命令的最后就行了。所以守护进程并非一定需要的。
public class test1 {
public static void main(String[] args) {
//卖票
selltickets s = new selltickets();
Thread t1 = new Thread(s, "窗口1");
Thread t2 = new Thread(s, "窗口2");
Thread t3 = new Thread(s, "窗口3");
t1.start();
t2.start();
t3.start();
}
}
class selltickets implements Runnable {
private static int num = 100;
Object o = new Object();
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o) {//每次只能有一个线程去操作
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "正在出售第" + num + "张票");
num--;
}
}
}
}
}
需求:多个线程复制一个文件
public class test21 {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:\\Users\\优小熊Xx\\Desktop\\m1.mp3");
File newfile = new File("C:\\Users\\优小熊Xx\\Desktop\\mm1.mp3");
long length = file.length();
long num = 3;
long copylength = length / num;
for (int i = 0; i < num; i++) {
long start = i * copylength;
long end = (i + 1) * copylength;
new ThreadCopy(start, end, file, newfile).start();
}
}
}
class ThreadCopy extends Thread {
long start;
long end;
RandomAccessFile in = null;
RandomAccessFile out = null;
public ThreadCopy(long start, long end, File file, File newfile) throws FileNotFoundException {
this.start = start;
this.end = end;
in = new RandomAccessFile(file, "rw");
out = new RandomAccessFile(newfile, "rw");
}
@Override
public void run() {
try {
in.seek(start);
out.seek(start);
int len = 0;
byte[] bytes = new byte[1024 * 1024];
if (start < end) {
while ((len = in.read(bytes)) != -1) {
start = start + len;
out.write(bytes, 0, len);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}