- Processes and Threads
- Multithreading: Can (concurrently) run multiple tasks (programs) in the operating system
- Multithreading: Multiple sequential streams (simultaneous) execution in the same application
- Thread execution Process
- Methods for creating threads
- Method 1: Define a thread class, he inherits the class thread and overrides the method run (), the method run (), called the thread body; Because Java supports only single inheritance, classes defined in this way cannot inherit other classes
- Multi-threaded program running mode and method
- Defines a class Firstthread inherits the thread, and then, using a replication method, executes the code in run () when the thread executes
- The Firstthread object is generated, and then the start () method of the object thread is called, and the thread enters the ready state, and the CPU gets into the execution state.
classFirstThread extends Thread{
publicvoid run(){
for(int i =0; i <10; i++){
System.out.println("FirstThread-->"+ i);
}
}
}
classTest{
publicstaticvoid main(String arg []){
//生成线程的对象
FirstThread ft =newFirstThread();
//启动线程
//ft.run(); 千万不能这样写,这样就是单线程,会先执行run()中的方法
ft.start();
//线程交替运行,并且没有规律
for(int i =0; i <10; i++){
System.out.println("main-->"+ i);
}
}
}
Results: D:\work\src>javac *.java D:\work\src>java testmain-->0firstthread-->0main-->1firstthread--> 1main-->2main-->3firstthread-->2firstthread-->3main-->4main-->5firstthread-->4main--> 6main-->7firstthread-->5firstthread-->6main-->8firstthread-->7main-->9firstthread--> 8firstthread-->9
- Multithreaded Data security
- Multi-threaded common data, there will be errors, need to introduce synchronous code block
- Methods for synchronizing threads
classMyThread implements Runnable{
int i =10;
publicvoid run(){
while(true){
/*
synchronized称为同步代码块;
this代表调用run()方法的对象,称为同步锁;
功能:获得同步锁才有资格运行代码;
**/
synchronized(this){
/*
currentThread()是Thread的静态方法,获取当前代码在哪个线程中运行;
Thread.currentThread().getName()可以获得线程的名字;
**/
System.out.println(Thread.currentThread().getName()+ i);
i--;
Thread.yield();
if(i <0){
break;
}
}
}
}
}
classTest{
publicstaticvoid main(String arg []){
MyThread myThread =newMyThread();
//生成两个Thread对象,但是这两个Thread对象共用一个线程体
Thread t1 =newThread(myThread);
Thread t2 =newThread(myThread);
/*每一个线程都有名字,可以通过Thread对象的setName()方法设置
也可以使用getName方法来获取线程的名字;**/
t1.setName("线程a");
t2.setName("线程b");
//分别启动两个线程
t1.start();
t2.start();
}
}
The result is: D:\work\src>javac *.java d:\work\src>java test thread B10 thread B9 thread B8 thread b7 thread B6 thread b5 thread b4 thread b3 thread b2 thread b1 thread B0 thread A-1
From for notes (Wiz)
Threads in 23.java